I am confused by this behaviour of Python(2.6.5), can someone shed light on why this happens?
class A():
mylist=[]
class B(A):
j=0
def addToList(self):
self.mylist.append(1)
b1 = B()
print len(b1.mylist) # prints 0 , as A.mylist is empty
b1.addToList()
print len(b1.mylist) # prints 1 , as we have added to A.mylist via addToList()
b2 = B()
print len(b2.mylist) # prints 1 !!! Why ?????
You need to do:
That way
self.mylistis an instance variable. If you define it outside of a method it is a class variable and so shared between all instances.In B if you define a constructor you’ll have to explicitly call A’s constructor:
This is explained (not very clearly) in the Python tutorial.