The common example when talking about class attributes in python, is the following:
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
>>> class B(object):
... cv = []
...
>>> b1 = B()
>>> b2 = B()
>>> b1.cv, b2.cv, B.cv
([], [], [])
>>> b1.cv.append(1)
>>> b1.cv, b2.cv, B.cv
([1], [1], [1])
>>> b2.cv.append(2)
>>> b1.cv, b2.cv, B.cv
([1, 2], [1, 2], [1, 2])
>>> B.cv.append(3)
>>> b1.cv, b2.cv, B.cv
([1, 2, 3], [1, 2, 3], [1, 2, 3])
It shows that class attribute is shared between class and all its instances.
But here is what happens when we reassign the value of class attribute, i.e. without the mutation of initial object bounded to a class attribute:
>>> class A(object):
... cv = 0
...
>>> a1 = A()
>>> a2 = A()
>>> a1.cv, a2.cv, A.cv
(0, 0, 0)
>>> a1.cv = 1
>>> a1.cv, a2.cv, A.cv
(1, 0, 0)
>>> a2.cv = 2
>>> a1.cv, a2.cv, A.cv
(1, 2, 0)
>>> A.cv = 3
>>> a1.cv, a2.cv, A.cv
(1, 2, 3)
Here we can see that each time this class attribute stores its unique value, and it will not be overridden in next assignments applied at both instance and class namespaces.
Why is this behavior like this?
I can't understand what kind of this logic may be that it leads to so 'not relevant' behaviors for "immutable" (A) and "mutable" (B) cases.. This makes me think of "no any sense of using class variables" as they may be prone to mistakes...
I hope that's me who does not see the light in this tunnel...