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 = 2 adds x to B’s own namespace (B.__dict__), so B stops looking at A.
  • C never set x, so C.x is a lookup that finds A.x. Changing A.x changes C.x with it.
  • Instances work the same way one level down: obj.x reads the class variable until obj.x = ... gives the instance its own.