1

I'm confused with below situation for python instance variable initialization, multiple instances (i1 and i2) get assigned with same "attr" object if I don't specify value for attr in constructor. Got different objects if I explicitly specify values in constructor.

sample code:

class MyClass:
    def __init__(self, x=1, attr=[]):
        print id(attr)
        self.attr = attr
        self.x = x

if __name__ == '__main__':
   
    i1 = MyClass()
    i2 = MyClass()
    i3 = MyClass(attr=[1,2])
    i4 = MyClass(attr=[1,2])

    print "i1:", vars(i1), id(i1.attr)
    print "i2:", vars(i2), id(i2.attr)
    print "i3:", vars(i3), id(i3.attr)
    print "i4:", vars(i4), id(i4.attr)

output:

38648928
38648928
38664672
38688648
i1: {'x': 1, 'attr': []} 38648928
i2: {'x': 1, 'attr': []} 38648928
i3: {'x': 1, 'attr': [1, 2]} 38664672
i4: {'x': 1, 'attr': [1, 2]} 38688648

Why i1 and i2 has the same 'attr' object?

Community
  • 1
  • 1
  • 1
    For the record, even though this is a duplicate, it's a well-written question. It's clear, has code, shows example output, demonstrates you figured out the crucial difference on your own, etc. – DSM Nov 02 '13 at 22:31
  • There should be like a Python FAQ with a link to that SO question. – Shashank Nov 02 '13 at 22:35
  • Thank you all for the help, now I understand after reading the existing post, but this was a surprise to me, Python is supposed to be "Least Astonishment" :) – user2948769 Nov 03 '13 at 03:00

1 Answers1

3

You create a default list attr=[]. The list created only 1 time. Every time you access the method without seeting attr, it uses the default list attr=[] he created earlier. In the second example, You constantly creating a new list every call of MyClass(attr=[1,2])

Weiner Nir
  • 1,435
  • 1
  • 15
  • 19