Method resolution for super(Class, obj).

ddtl this at is.invalid
Thu Sep 7 18:31:17 CEST 2006

Hello everybody.

Consider the following code:

class A(object):
    def met(self):
        print 'A.met'
class B(A):
    def met(self):
        print 'B.met'
class C(A):
    def met(self):
        print 'C.met'
class D(B,C):
    def met(self):
        print 'D.met'
d = D()

When executed, it prints:


The book (Python in a nutshell, 2nd edition) explains:

"The solution is to use built-in type super. super(aclass, obj), 
which returns a special superobject of object obj. When we look 
up an attribute (e.g., a method) in this superobject, the lookup 
begins after class aclass in obj's MRO."

But I don't understand - MRO means that when attribute is found 
somewhere in hierarchy, the search for it stops, that is: when 
d.met() is executed, it is supposed to print 'D met', call 
super(D,self).met() which should resolve met() to be B's attribute, 
and after B's met() is executed, we should be done. Why does the 
lookup proceeds from B to C as though met() wasn't found in B? 
Indeed, lookup order (according to a new-style MRO) is B, then C 
and at last A (because of a diamond inheritance), but only when 
attribute is not found in B it is looked up in C, and only if it 
is not found neither in B nor in C it is looked up in A...

What is different here?


More information about the Python-list mailing list