Default argument to __init__

Fredrik Lundh fredrik at pythonware.com
Mon Oct 10 18:28:20 CEST 2005


"netvaibhav at gmail.com" wrote:

> 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:

  /snip/

> 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?

it's explained in the FAQ:

    http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects

it's also mentioned in chapter 4 of the tutorial:

    http://docs.python.org/tut/node6.html#SECTION006710000000000000000

     "*Important warning*: The default value is evaluated only once. This
    makes a difference when the default is a mutable object such as a list,
    dictionary, or instances of most classes. "

    (the text then illustrates this with examples, and shows how to do things
     instead)

and in the description of "def" in the language reference:

    http://docs.python.org/ref/function.html

   "*Default parameter values are evaluated when the function definition
    is executed*. This means that the expression is evaluated once, when the
    function is defined, and that that same "pre-computed" value is used for
    each call. This is especially important to understand when a default para-
    meter is a mutable object, such as a list or a dictionary: if the function
    modifies the object (e.g. by appending an item to a list), the default
    value is in effect modified."

    (the text then shows how to do things instead)

> If so, what is the reason, as the behaviour I expect seems pretty logical.

that only means that you don't fully understand what "def" does (hint: it's
a statement, not a compiler directive).

</F>






More information about the Python-list mailing list