Method resolution for super(Class, obj).

Steve Holden steve at holdenweb.com
Thu Sep 7 15:04:05 EDT 2006


ddtl wrote:
> On 7 Sep 2006 10:42:54 -0700, in comp.lang.python you wrote:
> 
> 
>>Let's examine what the mro order is for class D:
>>
>>>>>D.mro()
>>
>>[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>,
>><class '__mai
>>n__.A'>, <type 'object'>]
>>
>>When you call d.met(), the call dispatches to the D.met() method.
>>After printing out 'D.met', you use super() to get the next class in
>>the mro order, and call that class's met method.
>>
>>As shown with the mro(), the class after D is B.  So B.met() is called.
>>Normally, we would be done.  But take a look at B's method!
>>
>>
>>>class B(A):
>>>    def met(self):
>>>        print 'B.met'
>>>        super(B,self).met()
>>
>>B.met calls super, and invokes the next met method!  So, the code does
>>exactly what you've asked it to do, and searches for the next class
>>after B in the mro list: class C.
> 
> 
> But when super(B,self).met() is invoked, isn't it supposed to look
> at MRO order of *B*, which is:
> 
> (<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)
> 
No, that's the mistake people often make. An instance of type B would 
see B's MRO, but an instance of type D sees D's MRO.

> and B doesn't have any relation with C, that is: A's met() is the to
> be called as a result. In effect, what you say impies that a call to
> super() is context dependant - if super(B,self).met() is invoked as
> a result of a call to D().met(), the effect is different from the effect 
> of a call to B().met(). But a documentation of a super() doesn't mention
> anything like that (or at least I didn't find it), and it seems a 
> significant piece of information. Doesn't it imply that there should 
> be another explanation?

It's all rather better explained in the Nutshell Guide than it is in the 
Python documentation. But basically you've got it right: it's the class 
of the *instance* that determines the MRO used by super().

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list