strange behaviour with keyword arguments and inheritance

matthewperpick matthewperpick at gmail.com
Tue Apr 17 17:06:03 CEST 2007


cool .. thanks everyone. here is the aforementioned faq.

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

On Apr 17, 5:16 am, Arnaud Delobelle <arno... at googlemail.com> wrote:
> matthewperpick wrote:
> > Check out this toy example that demonstrates some "strange" behaviour
> > with keyword arguments and inheritance.
>
> > =================================
>
> > class Parent:
> >     def __init__(self, ary = []):
> >         self.ary = ary
>
> [snip]
>
> As pointed out earlier, default values for arguments are evaluated
> when the function is defined, not when it is called.  This creates
> confusion if this value is mutable and later mutated; I got confused
> by it when I started python.  So it is often not a good idea to use
> mutable objects as default arguments.
>
> A simple fix:
>
> def __init__(self, ary=None):
>     if ary is None: ary = []
>    self.ary = ary
>
> --
> Arnaud





More information about the Python-list mailing list