Default argument to __init__
Larry Bates
larry.bates at websafe.com
Mon Oct 10 11:29:14 EDT 2005
This comes up on the list about once a week on this list.
See:
http://www.nexedi.org/sections/education/python/tips_and_tricks/python_and_mutable_n/view
-Larry Bates
netvaibhav at gmail.com wrote:
> 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