Default argument to __init__
Steve Holden
steve at holdenweb.com
Mon Oct 10 11:19:36 EDT 2005
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.
>
The default value of the keyword argument is evaluated once, at function
declaration time. The idiom usually used to avoid this gotcha is:
def __init__(self, myarr=None):
if myarr is None:
myarr = []
This ensures each call with the default myarr gets its own list.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list