Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q4 of Q15
Python - Multiple Inheritance and Method Resolution
What will be the output of this code?
class A:
    def greet(self):
        return 'Hello from A'

class B:
    def greet(self):
        return 'Hello from B'

class C(A, B):
    pass

obj = C()
print(obj.greet())
AHello from C
BHello from B
CHello from A
DError: Ambiguous method
Step-by-Step Solution
Solution:
  1. Step 1: Understand method resolution order (MRO)

    Python looks for methods in the order of inheritance listed: A then B.
  2. Step 2: Check which greet method is called

    Class C inherits from A first, so greet from A is used.
  3. Final Answer:

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

    MRO picks first parent method = Hello from A [OK]
Quick Trick: First parent class method is used if not overridden [OK]
Common Mistakes:
MISTAKES
  • Assuming method from second parent is called
  • Expecting error due to ambiguity
  • Thinking child class defines greet

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes