Bird
0
0

Given this class structure, what will be the output of D().greet()?

hard📝 Application Q15 of 15
Python - Multiple Inheritance and Method Resolution

Given this class structure, what will be the output of D().greet()?

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().greet()
AHello from D 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 B Hello from C Hello from A
Step-by-Step Solution
Solution:
  1. Step 1: Determine MRO for class D

    D's MRO is D, B, C, A, object. super() calls follow this order.
  2. Step 2: Trace greet() calls

    D.greet() prints 'Hello from D' then calls B.greet(), which prints 'Hello from B' and calls C.greet(), which 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 D
  4. Quick Check:

    super() follows MRO chain [OK]
Quick Trick: super() calls follow MRO order in diamond inheritance [OK]
Common Mistakes:
  • Ignoring MRO order in super() calls
  • Assuming C's greet() runs before B's
  • Missing that all greet() methods run

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes