super() and multiple inheritance failure

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Sep 26 00:30:52 EDT 2009


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. So if I 
call super(PClass, self), I expected that since PClass does not inherit 
from NClass, nothing should be inherited from NClass.


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



-- 
Steven



More information about the Python-list mailing list