1

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 ?????

2 Answers 2

2

You need to do:

class A: 
     def __init__(self):
         self.mylist=[] 

That way self.mylist is 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:

class B(A):
    def __init__(self):
        A.__init__(self)

This is explained (not very clearly) in the Python tutorial.

Sign up to request clarification or add additional context in comments.

Comments

2

This code creates a shared mylist among all instances of A (or subclasses)

class A(): 
    mylist=[]  

What you want to do is:

class A(): 
    def __init__(self):
        self.mylist=[]  

What you've probably seen is people who do:

class A(): 
    somevariable = a
    def doit(self):
        self.somevariable = 5

This works because it creates a new "somevariable" attribute because you are doing an assignment. Before that all A instances share the same copy of somevariable. As long as you don't change the copy that is fine. When the variable is assigned to, then it gets replaced rather then modified. So that technique is only really safe when the values in question are immutable (i.e. you can't change them, you can only replace them) However, I think that's a really bad idea and you should always assign all variables in init

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.