Python Multiple Inheritance

I have 3 classes A, B and D as below

class A(object):
    def test(self):
        print "called A"

class B(object):
    def test(self):
        print "called B"

class D(A,B):
    def test(self):
        super(A,self).test()

inst_d=D()
inst_d.test()

----------------------------------------
Output:
  called B

Question: D.test()I'm calling super(A,self).test(). Why is it only B.test()called, although the method A.test()also exists?

+5
source share
3 answers

Because you said not to do it. In D.testyou told him to invoke the method of checking parent A - what does super.

Usually you want to use the current class name in the call super.

+6
source

super(A,self).test()means: call the method of the testobject after A in the selforder of the method resolution (mro).

using D.__mro__, you see that the resolution order of the method:

<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>

So, testof Bis called.

Python 3 super().test(), , . Python 2 : super(D,self).test()

0

Normally, the super is called with the current class name, and you let MRO python take care of which parent class it should call in accordance with the algorithm that it follows. This way your code will look like this for your behavior.

class D(A,B):
    def test(self):
        super(D,self).test()

Note super(D,self).test()

0
source

All Articles