Bird
Raised Fist0

Identify the error in the following code snippet using multiple inheritance:

medium📝 Debug Q14 of Q15
Python - Multiple Inheritance and Method Resolution

Identify the error in the following code snippet using multiple inheritance:

class X:
    def __init__(self):
        print('X init')

class Y:
    def __init__(self):
        print('Y init')

class Z(X, Y):
    def __init__(self):
        X.__init__(self)
        Y.__init__(self)

z = Z()
AClass Z should inherit only from one parent
BMissing call to <code>super().__init__()</code> in class Z
CDirectly calling parent <code>__init__</code> methods can cause problems in complex hierarchies
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Analyze direct calls to parent __init__ methods

    Calling X.__init__(self) and Y.__init__(self) directly bypasses Python's MRO and can cause issues if the hierarchy grows complex.
  2. Step 2: Understand best practice

    Using super().__init__() respects MRO and avoids duplicate or missed calls.
  3. Final Answer:

    Directly calling parent __init__ methods can cause problems in complex hierarchies -> Option C
  4. Quick Check:

    Use super() to avoid init call issues [OK]
Quick Trick: Avoid direct parent calls; use super() instead [OK]
Common Mistakes:
MISTAKES
  • Thinking direct calls are always safe
  • Ignoring MRO and its importance
  • Believing multiple inheritance requires single parent only

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes