Bird
Raised Fist0

Given these classes, how can you ensure that a method process() defined in multiple parents is called exactly once in the correct order?

hard🚀 Application Q9 of Q15
Python - Multiple Inheritance and Method Resolution

Given these classes, how can you ensure that a method process() defined in multiple parents is called exactly once in the correct order?

class A:
    def process(self):
        print('A')

class B(A):
    def process(self):
        print('B')
        super().process()

class C(A):
    def process(self):
        print('C')
        super().process()

class D(B, C):
    def process(self):
        print('D')
        # What to call here?
ADo not call any parent method in <code>D.process()</code>.
BCall <code>B.process(self)</code> and <code>C.process(self)</code> directly.
CCall only <code>A.process(self)</code> in <code>D.process()</code>.
DCall <code>super().process()</code> in <code>D.process()</code>.
Step-by-Step Solution
Solution:
  1. Step 1: Understand MRO and super() chaining

    Using super().process() in all classes ensures each method is called once following MRO.
  2. Step 2: Apply super() in D.process()

    Calling super().process() in D.process() continues the chain through B, C, and A.
  3. Final Answer:

    Call super().process() in D.process(). -> Option D
  4. Quick Check:

    super() chains calls once in MRO order [OK]
Quick Trick: Use super() in all overrides to chain calls once [OK]
Common Mistakes:
MISTAKES
  • Calling parent methods directly causing duplicates
  • Skipping super() call in child method
  • Assuming only one parent method runs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes