5

I have 3 classes A,B and D as given 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: In D.test(), I am calling super(A,self).test(). Why is only B.test() called even though the method A.test() also exists?

1

3 Answers 3

6

Because you've told it not to. In D.test you've told it to call the test method of the parent of A - that's what super does.

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

Sign up to request clarification or add additional context in comments.

5 Comments

Also, the other classes need to also call super() to get the next class in the MRO.
And "normally" might as well be "pretty much always"; a hypothetical use case for skipping to a random place in the method resolution order would probably be rather exotic.
The answer is a little unclear - B is not the parent of A, so it isn't obvious why B.test() is called.
Thanks Daniel ,in this case mro will start from parent of A not from class A got it.
@Anoop: Exactly. The first parameter to super() indicates where the currently executing method is in the MRO that built by starting at the type of the second parameter. Then the method called through the resulting proxy will be the next one in the MRO after the current one.
0

super(A,self).test() means : call the test method of the object after A in self's method resolution order (mro) .

using D.__mro__ you see the the method resolution order is:

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

So test of B is called.

In Python 3 you only have to type super().test() and it does what you want. In Python 2 you need to type : super(D,self).test()

Comments

0

Usually the super is called with the current class name and you let the MRO of python to take care which parent class it should call according to the algorithm it follows. So your code will look like this, for the behavior you intend.

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

Note super(D,self).test()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.