strange behaviour with keyword arguments and inheritance

matthewperpick matthewperpick at gmail.com
Mon Apr 16 20:56:05 EDT 2007


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.




More information about the Python-list mailing list