Bird
Raised Fist0

Identify the error in this code snippet related to multiple inheritance:

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

Identify the error in this code snippet related to multiple inheritance:

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

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

class C(A, B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)

c = C()
AMissing call to <code>super().__init__()</code> causes syntax error.
BDirectly calling parent <code>__init__</code> methods can cause duplicate calls in complex hierarchies.
CClass C should inherit from B before A.
DPython does not support multiple inheritance of classes with <code>__init__</code>.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze direct parent __init__ calls

    Calling A.__init__(self) and B.__init__(self) directly can cause problems if classes have common ancestors or complex MRO.
  2. Step 2: Best practice is to use super()

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

    Directly calling parent __init__ methods can cause duplicate calls in complex hierarchies. -> Option B
  4. Quick Check:

    Use super() to avoid duplicate init calls [OK]
Quick Trick: Avoid direct parent calls; use super() in __init__ [OK]
Common Mistakes:
MISTAKES
  • Calling parent __init__ methods directly
  • Ignoring MRO in constructors
  • Assuming multiple inheritance disallows __init__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes