这里有一个关于实例变量的新手Python问题.
考虑以下Python 2.7类定义:
class Foo(object):
a = 1
def __init__(self):
self.b = 2
def __repr__(self):
return "%s" % self.__dict__
Run Code Online (Sandbox Code Playgroud)
现在,当我创建一个实例Foo,Foo.__dict__包含b但不是a.
>>> x=Foo()
>>> x
{'b': 2}
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', 'a', 'b']
>>> x.__dict__
{'b': 2}
Run Code Online (Sandbox Code Playgroud)
在这里,我认为我对Python的方式有了很好的把握.
x.a和之间有什么区别x.b?据我所知,它们都是实例变量.
编辑:好的,重新阅读Python文档,我看到这Foo.a是一个类属性而不是实例变量.嗯...我想混淆来自于我可以为其分配一个新值,x.a而新值只影响x实例 - 我想我现在正在Foo.a …