Subclasses Read Class Variables From Their Parent Until They Set Their Own
A class variable lives in the namespace of the class that defines it. A subclass that doesn't set the variable itself reads it from its parent, following the method resolution order, so changing the parent's value changes what the subclass sees.
>>> class A:
... x = 1
...
>>> class B(A):
... pass
...
>>> class C(A):
... pass
...
>>> print(A.x, B.x, C.x)
1 1 1
>>> B.x = 2
>>> print(A.x, B.x, C.x)
1 2 1
>>> A.x = 3
>>> print(A.x, B.x, C.x)
3 2 3
B.x = 2addsxtoB’s own namespace (B.__dict__), soBstops looking atA.Cnever setx, soC.xis a lookup that findsA.x. ChangingA.xchangesC.xwith it.- Instances work the same way one level down:
obj.xreads the class variable untilobj.x = ...gives the instance its own.