super() and multiple inheritance failure

Chris Rebert clp2 at rebertia.com
Sat Sep 26 02:06:09 EDT 2009


On Fri, Sep 25, 2009 at 9:30 PM, Steven D'Aprano
<steve at remove-this-cybersource.com.au> wrote:
> On Fri, 25 Sep 2009 20:15:54 -0700, Chris Rebert wrote:
>
>>> Inside MyClass().method(n), I dispatch to either NClass.method() or
>>> PClass.method() depending on the value of the argument n. The correct
>>> class is called, but then the *other* class method is called as well.
>>> E.g. this is what I expect:
>>>
>>> MyClass().method(2)
>>> ->  calls PClass.method
>>>    -> calls BaseClass.method
>>>
>>> but this is what I get:
>>>
>>> MyClass().method(2)
>>> ->  calls PClass method
>>>    ->  calls NClass.method
>>>        -> calls BaseClass.method
>>>
>>>
>>> and similarly for negative arguments, swapping PClass and NClass.
>>>
>>> First off, is this the expected behaviour? I seems strange to me, can
>>> somebody explain why it is the nominally correct behaviour?
>>
>> Pretty darn sure it's expected. super() follows the MRO, which in this
>> case is M, P, N, B, o; thus, the super() of an M instance from a P
>> method is indeed N.
>
> I was expecting super() to look at the class, not the instance.

To be pedantic, it looks at the type of instance, taking into account
the class passed to it.

>> This would normally be useful as one typically wants to call the
>> "parent" methods of all ancestor classes for which the method is
>> defined, rather than picking-and-choosing as MyClass.method() does.
>
> Gotcha. I was expecting super() to call the first matching ancestor
> method, not all of them.

Well, it doesn't call all of them, it's just that each method
implementation usually calls super() itself; thus, in concert, in
normal usage, all the methods end up getting called.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list