为什么更改实例变量也会改变静态变量?

RNA*_*RNA 0 python attributes class

我对下面的Python行为感到困惑.为什么第二个和第三个实例(b,c) i的属性是类属性ia行为不同?

In [47]: class Foo:
    ...:     i=0
    ...:

In [48]: a = Foo()

In [49]: a.i = 1

In [50]: a.i
Out[50]: 1

In [51]: Foo.i
Out[51]: 0

In [52]: b = Foo()

In [53]: b.i
Out[53]: 0

In [54]: Foo.i is b.i
Out[54]: True

In [55]: Foo.i is a.i
Out[55]: False

In [56]: c = Foo()

In [57]: Foo.i is c.i
Out[57]: True
Run Code Online (Sandbox Code Playgroud)

wim*_*wim 6

这是发生了什么.当你这样做时:

a.i = 1
Run Code Online (Sandbox Code Playgroud)

您可以使用隐藏类属性的名称创建实例变量.但是class属性仍然存在:

>>> class Foo:
...     i = 0
...     
>>> a = Foo()
>>> Foo.i
0
>>> a.i = 69
>>> a.i
69
>>> a.__class__.i
0
>>> del a.i  # deletes the instance attribute, resolving lookup on class
>>> a.i
0
Run Code Online (Sandbox Code Playgroud)

要查看实例命名空间中的内容,请查看实例dict:

>>> a = Foo()
>>> a.__dict__
{}
>>> a.i = 1
>>> a.__dict__
{'i': 1}
Run Code Online (Sandbox Code Playgroud)