Bird
Raised Fist0

What will be the output of the following code?

medium📝 Predict Output Q13 of Q15
Python - Multiple Inheritance and Method Resolution

What will be the output of the following code?

class A:
    def greet(self):
        print('Hello from A')

class B(A):
    def greet(self):
        print('Hello from B')
        super().greet()

class C(A):
    def greet(self):
        print('Hello from C')
        super().greet()

class D(B, C):
    def greet(self):
        print('Hello from D')
        super().greet()

d = D()
d.greet()
AHello from D Hello from B Hello from C Hello from A
BHello from D Hello from C Hello from B Hello from A
CHello from D Hello from B Hello from A
DHello from D Hello from C Hello from A
Step-by-Step Solution
Solution:
  1. Step 1: Understand the method resolution order (MRO)

    For class D(B, C), the MRO is D > B > C > A. Calling super() follows this order.
  2. Step 2: Trace the calls

    d.greet() prints 'Hello from D', then calls B.greet() which prints 'Hello from B' and calls C.greet(). C.greet() prints 'Hello from C' and calls A.greet(), which prints 'Hello from A'.
  3. Final Answer:

    Hello from D Hello from B Hello from C Hello from A -> Option A
  4. Quick Check:

    MRO order = D, B, C, A [OK]
Quick Trick: Follow MRO order when super() is called [OK]
Common Mistakes:
MISTAKES
  • Ignoring MRO and calling parents in wrong order
  • Assuming super() calls only immediate parent
  • Missing one of the parent class prints

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes