Default argument to __init__

netvaibhav at gmail.com netvaibhav at gmail.com
Mon Oct 10 16:50:12 CEST 2005


Hi All:

Here's a piece of Python code and it's output. The output that Python
shows is not as per my expectation. Hope someone can explain to me this
behaviour:

[code]
class MyClass:
        def __init__(self, myarr=[]):
                self.myarr = myarr

myobj1 = MyClass()
myobj2 = MyClass()

myobj1.myarr += [1,2,3]

myobj2.myarr += [4,5,6]

print myobj1.myarr
print myobj2.myarr
[/code]

The output is:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

Why do myobj1.myarr and myobj2.myarr point to the same list? The
default value to __init__ for the myarr argument is [], so I expect
that every time an object of MyClass is created, a new empty list is
created and assigned to myarr, but it seems that the same empty list
object is assigned to myarr on every invocation of MyClass.__init__

It this behaviour by design? If so, what is the reason, as the
behaviour I expect seems pretty logical.

Thanks.

Vaibhav




More information about the Python-list mailing list