修改后的第一程序
class foo:
foo = 'K-Dawg'
def __str__(self):
print dir(self)
return self.foo
obj = foo()
print obj
修改后的第二计划
class foo:
def __init__(self):
print locals()
foo = 'K-Dawg'
print locals()
def __str__(self):
print locals()
return self.foo
obj = foo()
print obj
我只是包括一些打印语句。如果你看看每个程序的输出结果,你将能够弄清楚到底发生了什么。
第一个程序将打印
['__doc__', '__module__', '__str__', 'foo']
K-Dawg
我们可以看到,foo
已经存在的对象。实际上,在这种情况下,foo
是一个类变量(与类实例无关,如果来自C,C++或JAVA背景,则可以将其视为一个静态变量,它绑定到类而不是Object)。
第二个程序将打印
{'self': <__main__.foo instance at 0x7f528aa90488>}
{'self': <__main__.foo instance at 0x7f528aa90488>, 'foo': 'K-Dawg'}
{'self': <__main__.foo instance at 0x7f11f236d488>}
AttributeError: foo instance has no attribute 'foo'
这显然告诉我们,变量foo
在__init__
功能得到了创建,但是当它到达__str__
它不可。这意味着在__init__
中创建的foo
变量对于该函数是本地的。
如果你想创建的对象的变量,你应该做这样的事情
class foo:
def __init__(self):
print locals()
self.foo = 'K-Dawg' # Note the self keyword at the beginning
print locals()
def __str__(self):
print locals()
return self.foo
obj = foo()
print obj
输出
{'self': <__main__.foo instance at 0x7fe0e2da24d0>}
{'self': <__main__.foo instance at 0x7fe0e2da24d0>}
{'self': <__main__.foo instance at 0x7fe0e2da24d0>}
K-Dawg
self
指向类的当前实例,我们通过做self.foo = 'K-Dawg'
附加一个名为foo
的变量。这就是为什么这是有效的。
就在旁边注意,'__init__'不是一个构造函数。 – Hyperboreus