我是python的新手,了解到类属性就像C++中的静态数据成员。然而,在尝试下面的代码后我感到困惑:python:class属性和实例属性
>>> class Foo:
... a=1
...
>>> f1=Foo();
>>> f2=Foo()
>>> f1.a
1
>>> f1.a=5
>>> f1.a
5
>>> f2.a
1
不应该f2.a也等于5吗?
如果被定义为一个列表,而不是一个整数,该行为是正常的:
>>> class Foo:
... a=[]
...
>>> f1=Foo();
>>> f2=Foo()
>>> f1.a
[]
>>> f1.a.append(5)
>>> f1.a
[5]
>>> f2.a
[5]
我看着 Python: Difference between class and instance attributes,但它并没有回答我的问题。
任何人都可以解释为什么区别?由于
可能的重复[如何避免让Python类数据在实例间共享?](http:// stackoverflow。com/questions/1680528/how-do-i-avoid-having-python-class-data-shared-among-instances) –