Classes & Objects · Question 16 · Hard

D inherits from both B and C, and B and C both inherit from A. Which who() runs, and what is D's method resolution order?

class A:
    def who(self): return "A"
class B(A):
    def who(self): return "B"
class C(A):
    def who(self): return "C"
class D(B, C):
    pass

print(D().who(), [k.__name__ for k in D.__mro__])
  1. B ['D', 'B', 'A', 'C', 'object']
  2. C ['D', 'C', 'B', 'A', 'object']
  3. B ['D', 'B', 'C', 'A', 'object']
  4. A ['D', 'A', 'B', 'C', 'object']
Answer and explanation

Answer: C. B ['D', 'B', 'C', 'A', 'object']

Explanation: Python searches D first, then the parents in the order they are listed, B then C, and only after both does it go to their shared parent A. B is found first, so who() returns B.

Previous: B is a child of A. What do isinstance, a direct type comparison and issubclass… · Next: Every class in this diamond calls super().go(). What string does D().go() build?

Practise classes & objects

Try a fresh set of classes & objects questions with an explanation after every answer, free and without signing up: Classes & Objects practice. Or sit a full placement mock test.

More classes & objects questions

More python practice

Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge