strange behaviour with keyword arguments and inheritance

Jun.Jin.act+group.python@gmail.com Jun.Jin.act at gmail.com
Mon Apr 16 21:07:45 EDT 2007


On Apr 17, 8:56 am, "matthewperpick" <matthewperp... at gmail.com> 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
>
>     def append(self):
>         self.ary.append(1)
>
> class Child(Parent):
>     def __init__(self):
>         Parent.__init__(self)
>         self.append()
>
> def main():
>     a = Child()
>     print a.ary
>     b = Child()
>     print b.ary
>
> main()
>
> =====================================
>
> You would think the output of this program would be [1], [1]. But
> strangely enough the output is [1,], [1,1]. I suppose that the
> Parent.__class__ object is only created once and thus the keyword
> argument always refers to the same thing, but I don't know. I have a
> very rudimentary understading of python's guts, but I would still call
> the behaviour unexpected. Or perhaps I should rtfm?
>
> Any thoughts would be much appreciated. Thanks.

A slight modification of init-ing the parent can give you the expected
output.

class Child(Parent):
    def __init__(self):
        Parent.__init__(self, [])
        self.append()





More information about the Python-list mailing list