来自深入 Python:
Class attributes are available both through direct reference to the class and through any instance of the class.
Class attributes can be used as class-level constants, but they are not really constants. You can also change them.
所以我在 IDLE 中输入:
IDLE 2.6.5
>>> class c:
counter=0
>>> c
<class __main__.c at 0xb64cb1dc>
>>> v=c()
>>> v.__class__
<class __main__.c at 0xb64cb1dc>
>>> v.counter += 1
>>> v.counter
1
>>> c.counter
0
>>>
那我做错了什么?为什么类变量不通过直接引用类和类的任何实例来维护其值。
请您参考如下方法:
因为 int 在 python 中是不可变的
v.counter += 1
将 v.counter 重新绑定(bind)到一个新的 int 对象。重新绑定(bind)会创建一个实例属性来屏蔽类属性
如果您查看 v.counter 的 id(),就可以看到这种情况的发生
>>> id(v.counter)
149265780
>>> v.counter+=1
>>> id(v.counter)
149265768
在这里您可以看到 v 现在在其 __dict__ 中有一个新属性
>>> v=c()
>>> v.__dict__
{}
>>> v.counter+=1
>>> v.__dict__
{'counter': 1}
对比 counter 可变的情况,例如 list
>>> class c:
... counter=[]
...
>>> v=c()
>>> v.counter+=[1]
>>> c.counter
[1]
>>>
