This script:
class testa():
a = []
class testb():
def __init__(self):
self.a = []
ta1 = testa(); ta1.a.append(1); ta2 = testa(); ta2.a.append(2)
tb1 = testb(); tb1.a.append(1); tb2 = testb(); tb2.a.append(2)
print ta1.a, ta2.a, tb1.a, tb2.a
produces this output:
[1, 2] [1, 2] [1] [2]
but I expected
[1] [2] [1] [2]
Why was I wrong? The definitions of testa and testb seem equivalent to me, so why should behavior change so drastically?!
EDIT: This seems unintuitive because it is different from how other types like int and str behave. For some reason lists are created as class variables when not initialized in init, but ints and strs are created as object variables no matter what.
In testa the variable a is a class variable and is shared between all instances. ta1.a and ta2.a refer to the same list.
In testb the variable a is an object variable. Each instance has its own value.
See Class and Object Variables for more details.
One is a class variable, the other is an instance variable.
Class vars are shared between all members of the class, instance vars are unique to each instance.
http://docs.python.org/tutorial/classes.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With