Python Question

class variable oddities without self

I'm trying to grasp on the idea on how the class variables work. And to my knowledge class variables are shared between the class instances (objects).
So within THAT idea, if I change the class variable, the value should change to all the class instances...
...BUT, this seems not to be always the case.

Below is an simplified example:

class A:
name = "Dog"

a1 = A()
a2 = A()

# These both change the value only for an instance = "Cat" += " is an animal"

class B:
number = 0

b1 = B()
b2 = B()

# Again only changes value for an instance
b1.number = 2
print(b1.number, b2.number)

# This is the weird one.
class C:
lista = []

c1 = C()
c2 = C()

# Changes the value for BOTH/ALL instances.
print(c1.lista, c2.lista)

# But this one only changes the value for an instance.
c1.lista = [1, 2, 3]
print(c1.lista, c2.lista)

Answer Source

Class variables are shared between instances until the moment you assign to an instance variable by the same name. (As an aside, this behavior is useful for declaring defaults in inheritance situations.)

>>> class X:
...   foo = "foo"
>>> a = X()
>>> b = X()
>>> c = X()
>>> = "bar"
>>> id(
>>> id(
>>> id(

Your list example mutates the shared instance first, then reassigns a new value to c1.lista, but c2.lista remains the shared instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download