Search code examples
pythonscopeclass-members

Puzzling scope behaviour


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!


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.