Bird
0
0

Find the error in this code related to the diamond problem:

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

Find the error in this code related to the diamond problem:

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):
    def greet(self):
        C.greet(self)

D().greet()
ACalling C.greet(self) ignores B's greet and breaks MRO.
BMissing super() call causes infinite recursion.
CSyntax error in class D definition.
DNo error; code runs fine.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze method call in D.greet()

    D.greet() calls C.greet(self) directly, skipping B's greet() and ignoring MRO.
  2. Step 2: Understand diamond problem and MRO importance

    By calling C.greet(self) directly, it breaks the expected MRO chain and can cause unexpected behavior.
  3. Final Answer:

    Calling C.greet(self) ignores B's greet and breaks MRO. -> Option A
  4. Quick Check:

    Direct base class call breaks MRO [OK]
Quick Trick: Avoid direct base class calls; use super() to respect MRO [OK]
Common Mistakes:
  • Thinking code has syntax error
  • Missing that direct call breaks MRO
  • Assuming no error occurs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes