Mikko-Pentti Einari Eronen Mikko-Pentti Einari Eronen - 11 months ago 56
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
a1.name = "Cat"
a2.name += " is an animal"
print(a1.name, a2.name)

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()
>>> c.foo = "bar"
>>> id(a.foo)
>>> id(b.foo)
>>> id(c.foo)

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