I learned that Python 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
What is the difference between class and instance attributes?, but it doesn’t answer my question.
Can anyone explain why the difference?
You’re not doing the same thing in your second example. In you first example, you are assigning
f1.aa new value:In your second example, you are simply extending a list:
This doesn’t change what
f1.ais pointing to. If you were instead to do this:You would find that this behaves the same as your first example.
But consider this example:
In this example, we’re actually changing the value of the class attribute,
and the change is visible in all instances of the class. When you
type:
You’re overriding the class attribute with an instance attribute.