修改后的第一个程序
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 背景,这可以被认为是一个绑定到类而不是对象的静态变量。)
第二个程序将打印
{'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__
。这意味着foo
创建的变量是__init__
该函数的本地变量。
如果你想在对象中创建变量,你应该做这样的事情
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
指向类的当前实例,我们正在附加一个foo
通过doing调用的变量self.foo = 'K-Dawg'
。这就是为什么它有效。