Python中的类属性/变量

时间:2014-10-30 13:29:04

标签: python class

两个例子;

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?这有什么区别?哪种方式更适合使用?

2 个答案:

答案 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)

somethingself.something不同。当您访问x.somethingy.something时,您正在访问绑定到该实例的版本。原始somethingtype的本地,而不是该类型的对象:

>>> Foo1.something
0
>>> Foo1(42).something
42
相关问题