Question

I can't seem to understand what is going on here:

class testclass: 

    def __init__(self): 
        print "new instance" 
    myList=[] 

if __name__ == "__main__":  

    inst1=testclass() 
    inst1.myList.append("wrong") 

    inst2=testclass() 
    inst2.myList.append("behaviour") 

    print "I get the",inst2.myList

The output is:

new instance
new instance
I get the ['wrong', 'behaviour']

I would have expected that the list in inst1 knows nothing about the list in inst2, but somehow it looks like the scope of myList trascends the instantiation of the class. I find this very unsettling and puzzling, or am I missing something here?

Thanks!

Was it helpful?

Solution

The way you defined myList is a class attribute.

The behaviour your looking for is the one of an object attribute:

class testclass:
    def __init__(self): 
        print "new instance"
        self.myList = []

Let's try it:

>>> t1 = testclass()
new instance
>>> t2 = testclass()
new instance
>>> t1.myList.append(1)
>>> t2.myList.append(2)
>>> t1.myList
[1]
>>> t2.myList
[2]

If you're interested in class attributes take a look at the Class documentation. Since classes in Python are objects too, like (almost) everything in Python, they can have their own attributes.

OTHER TIPS

The way you declared myList inside the class makes it a class attribute. if you intended to have an instance attribute, declare it like this and it will have the expected behavior:

class testclass:
    def __init__(self): 
        print "new instance" 
        self.myList=[]

Yes, because that is what class attributes are for. If you want an instance variable, you need to declare it on the instance itself - usually with self inside a method.

myList is initialised at class instantiation time, because it is declared in the body of the class, not at object instantiation time.

Such properties are then shared with instances, until a variable with the same name is created on the instance.

So, in your case, you are using each object to access the same myList object (and append a value to it).

class testclass:

    def __init__(self):
        self.myList=[]
        print "new instance"

If you want myList to be an instance variable, you should define self.myList inside the init function. Then you should get the behavior you expect. As you have it now, I think myList is a class variable, and will be shared by all instances of the class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top