Bird
0
0

Given these classes:

hard📝 Application Q9 of 15
Python - Multiple Inheritance and Method Resolution
Given these classes:
class A:
    def method(self):
        return "A"

class B(A):
    def method(self):
        return "B"

class C(A):
    def method(self):
        return "C"

class D(B, C):
    pass

obj = D()
print(obj.method())

What is the output and why?
AB, because B is the first parent in D's inheritance list
BC, because C overrides B
CA, because both B and C call A's method
DError due to ambiguous method resolution
Step-by-Step Solution
Solution:
  1. Step 1: Understand method resolution order (MRO) in multiple inheritance

    D inherits from B and C. Python checks B first, then C, then A.
  2. Step 2: Identify which method is called

    B overrides method to return "B", so obj.method() returns "B".
  3. Final Answer:

    B, because B is the first parent in D's inheritance list -> Option A
  4. Quick Check:

    MRO picks first parent's method = B [OK]
Quick Trick: First parent class method is used in multiple inheritance [OK]
Common Mistakes:
  • Assuming C's method is called
  • Expecting error due to multiple parents
  • Thinking base class A's method is called

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes