unexpected class behaviour

Jan Schäfer jan.patrick.schaefer at googlemail.com
Sun Sep 7 06:30:58 EDT 2008


Hi all,

can anyone explain the behaviour of the following code sniplet:

---> schnipp <---
class Base(object):
    def __init__( self, lst=[] ):
        self.varlist = lst

    def addVar( self, var ):
        self.varlist.append(var)  
        
class Derived(Base):
    def __init__( self, var ):
        Base.__init__(self)
        self.addVar(var)

vars = ['foo', 'bar']

for ivar in vars:
    obj = Derived(ivar)
    print ivar, obj, obj.varlist
---> schnapp <---

After running (Python 2.5.1), I get the following output:
foo <__main__.Derived object at 0xb7c608cc> ['foo']
bar <__main__.Derived object at 0xb7c6092c> ['foo', 'bar']

So, I get two different objects, but how does the 'foo' get into the second
varlist? I'm a little bit confused about this, any ideas?

Thanks in advance

Jan



More information about the Python-list mailing list