开发者

OOPs paradigm in Python

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜