tags:

views:

127

answers:

1

Here is something I've been having a doubt about. Consider the following snippet.

class A(object):
    def check(self):
        super(A, self).check()
        print "inside a"

class B(object):
    def check(self):
        print "inside b"

class C(A, B):
    pass

c = C()
c.setup()

Now this gives the output,

inside b
inside a

Passing this through pdb i see that on reaching A.setup(), B.setup() is being called. However, the call from A is to the check method of its superclass; as it does not exist the call moves from that point to B.check().

  1. Could someone explain or point me to a document which explains how this works internally? I could'nt find any.
  2. Could someone show me a similar implementation in C++/Java? I think comparing it with other languages would help me understand the problem at hand better.

Many thanks.

+8  A: 

The algorithm is explained in this excellent article.

In short,

super(A,self) looks in self.__class__.__mro__ for the next class after A.

In your case, self is c, so self.__class__ is C. C.__mro__ is [C,A,B,object]. So the next class in the MRO after A happens to be B.

So super(A,self) returns a super object which behaves like B as far as attribute lookup is concerned.

super(A, self).check() thus calls B.check().

The C3 algorithm Python uses to generate the MRO (Method Resolution Order) is also described in a little more detail in this essay by Michele Simionato.

unutbu
+1 for delaying my fourth of July activities with an "oh crap I can't stop reading this" article.
sdolan
Oh yes, my family loves it when I regale them the full story of Python attribute lookup while we watch the big screensaver in the sky.
unutbu