python - class variable oddities without self -


this question has answer here:

i'm trying grasp on idea on how class variables work. , knowledge class variables shared between class instances (objects). within idea, if change class variable, value should change class instances... ...but, seems not case.

below simplified example:

class a:     name = "dog"  a1 = a() a2 = a()  # these both change value instance a1.name = "cat" a2.name += " animal" print(a1.name, a2.name)   class b:     number = 0  b1 = b() b2 = b()  # again changes value instance b1.number = 2 print(b1.number, b2.number)   # weird one. class c:     lista = []  c1 = c() c2 = c()  # changes value both/all instances. c1.lista.append(5) c2.lista.append(6) print(c1.lista, c2.lista)  # 1 changes value instance. c1.lista = [1, 2, 3] print(c1.lista, c2.lista) 

class variables shared between instances until moment assign instance variable same name. (as aside, behavior useful declaring defaults in inheritance situations.)

>>> class x: ...   foo = "foo" ... >>> = x() >>> b = x() >>> c = x() >>> c.foo = "bar" >>> id(a.foo) 4349299488 >>> id(b.foo) 4349299488 >>> id(c.foo) 4349299824 >>> 

your list example mutates shared instance first, reassigns new value c1.lista, c2.lista remains shared instance.


Comments