Bird
0
0

What will be the output of this code?

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

What will be the output of this code?

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

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

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

class D(B, C):
    pass

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

    Class D inherits from B and C. Python looks for greet() in D, then B, then C, then A.
  2. Step 2: Identify which greet() is called

    D has no greet(), so it calls B's greet() first, printing 'Hello from B'.
  3. Final Answer:

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

    MRO chooses first parent method [OK]
Quick Trick: MRO calls first parent's method in order [OK]
Common Mistakes:
  • Assuming C's greet() is called
  • Expecting A's greet() to run
  • Thinking D has greet() method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes