instance variable weirdness

wietse wietse.j at gmail.com
Fri Apr 14 12:18:38 EDT 2006


Hello,

I have written the following script to illustrate a problem in my code:

class BaseClass(object):
    def __init__(self):
        self.collection = []

class MyClass(BaseClass):
    def __init__(self, name, collection=[]):
        BaseClass.__init__(self)
        self.name = name
        self.collection = collection

if __name__ == '__main__':
    seq = []
    inst = None
    for i in xrange(5):
        inst = MyClass(str(i))
        inst.collection.append(i)
        seq.append(inst)
        inst = None
    for i in xrange(5):
        inst = MyClass(str(i)+'~', [])
        inst.collection.append(i)
        seq.append(inst)
        inst = None
    for i in seq:
        print "Instance '%s'; collection = %s" % (i.name,
str(i.collection))

The output I get is:
>>>
Instance '0'; collection = [0, 1, 2, 3, 4]
Instance '1'; collection = [0, 1, 2, 3, 4]
Instance '2'; collection = [0, 1, 2, 3, 4]
Instance '3'; collection = [0, 1, 2, 3, 4]
Instance '4'; collection = [0, 1, 2, 3, 4]
Instance '0~'; collection = [0]
Instance '1~'; collection = [1]
Instance '2~'; collection = [2]
Instance '3~'; collection = [3]
Instance '4~'; collection = [4]
>>>

I don't understand why the first loop doesn't give the same result as
the second loop. Can somebody enlighten me?

Wietse




More information about the Python-list mailing list