0

Diamond Problem

class A():
   def method(self):
       print ("I am from class A")

class B(A):
   def method(self):
       print("I am from B")
       super().method()

class C(A):
   def method(self):
       print ("I am from class C")

class D(B,C):
   def method(self):
       print ("I am from class D")
       super().method()




d = D()

d.method()

I want to get the output as :

I am from class D
I am from B
I am from class A

However, i get the output as:

I am from class D
I am from B
I am from class C

How do i call method the method of A class using instance of D class? Is MRO a possible solution to this?

2
  • Just don't do multiple inheritance class D(B):? Commented Dec 12, 2017 at 11:37
  • 1
    @MikeMüller Agree, I am Able to do this without multiple inheritance however i am more interested in understanding the underlying MRO, which is sending control of Program to C class instead of A. Commented Dec 12, 2017 at 12:03

2 Answers 2

2

In Python 3 children always come in MRO before parents, this is needed to allow overrides work sensibly:

>>> D.__mro__
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

In multiple inheritance, super() does not simply refer to the parent, it is used to get the next class in MRO. If you know what method of what class you want to call, do it directly:

class D(B,C):
   def method(self):
       print("I am from class D")
       A.method(self)
Sign up to request clarification or add additional context in comments.

Comments

0
class A():
   def method(self):
       print ("I am from class A")

class B(A):
   def method(self):
       print("I am from B")
       A.method(self)

class C(A):
   def method(self):
       print ("I am from class C")

class D(B,C):
   def method(self):
       print ("I am from class D")
       super().method()




d = D()

d.method()

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.