I'm new to python and learned that class attributes are like static data members in C++. However, I got confused after trying the following code:
>>> class Foo:
... a=1
...
>>> f1=Foo();
>>> f2=Foo()
>>> f1.a
1
>>> f1.a=5
>>> f1.a
5
>>> f2.a
1
Shouldn't f2.a also equal 5?
If a is defined as a list instead of an integer, the behavior is expected:
>>> class Foo:
... a=[]
...
>>> f1=Foo();
>>> f2=Foo()
>>> f1.a
[]
>>> f1.a.append(5)
>>> f1.a
[5]
>>> f2.a
[5]
I looked at Python: Difference between class and instance attributes, but it doesn't answer my question.
Can anyone explain why the difference? Thanks
See Question&Answers more detail:os