Bird
Raised Fist0

What will be the output of the following Python code?

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

What will be the output of the following Python code?

class X:
    def speak(self):
        print('X speaks')

class Y(X):
    def speak(self):
        print('Y speaks')

class Z(X):
    def speak(self):
        print('Z speaks')

class W(Y, Z):
    pass

w = W()
w.speak()
AY speaks
BX speaks
CZ speaks
DError due to ambiguous method call
Step-by-Step Solution
Solution:
  1. Step 1: Analyze class W inheritance

    W inherits from Y and Z, both inherit from X.
  2. Step 2: Check method resolution order (MRO)

    Python uses C3 linearization; W's MRO is W > Y > Z > X.
  3. Step 3: Determine which speak() is called

    Since Y appears before Z, Y's speak() is called.
  4. Final Answer:

    Y speaks -> Option A
  5. Quick Check:

    Check W.__mro__ confirms order [OK]
Quick Trick: Python calls first parent method in MRO [OK]
Common Mistakes:
MISTAKES
  • Assuming Z's speak() is called because it appears second
  • Expecting an error due to diamond ambiguity
  • Thinking base class X's method is called

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes