两个例子;
class Foo1:
something = 0
def __init__(self, n):
self.something = n
和
class Foo2:
def __init__(self, n):
self.something = n
这两个类似乎都有相同的行为:
x = Foo1(42)
y = Foo2(36)
print x.something
# will print 42
print y.something
# will print 36
但是在类Foo1
中变量self.something
(在构造函数中)实际上是在类的开头定义的变量something
?这有什么区别?哪种方式更适合使用?
答案 0 :(得分:3)
不同之处在于,在第一种情况下,您可以在不使用对象(或实例)的情况下访问数据属性。在第二种情况下,你不能。请检查以下代码段:
>>> class Foo1:
... something = 0
... def __init__(self, n):
... self.something = n
...
>>> Foo1.something
0
>>> class Foo2:
... def __init__(self, n):
... self.something = n
...
>>> Foo2.something
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class Foo2 has no attribute 'something'
>>>
希望我能澄清一下。有关详情,请参阅:https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables
答案 1 :(得分:2)
something
与self.something
不同。当您访问x.something
或y.something
时,您正在访问绑定到该实例的版本。原始something
是type
的本地,而不是该类型的对象:
>>> Foo1.something
0
>>> Foo1(42).something
42