Repaso
EspaƱol
PythonAdvancedPY-09

What does this print?

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

print(D().hi(), [k.__name__ for k in D.__mro__])

Options

  1. B ['D', 'B', 'C', 'A', 'object'] (Correct option)
  2. C ['D', 'C', 'B', 'A', 'object']
  3. B ['D', 'B', 'A', 'C', 'object']
  4. A ['D', 'A', 'B', 'C', 'object']

Answer

B ['D', 'B', 'C', 'A', 'object']

Why

When a class has several parents, Python needs a fixed order to search for methods. That order is the MRO (Method Resolution Order).

Python builds it with an algorithm called C3: the class itself first, then the parents from left to right, and a shared grandparent (A) only after all of its children.

For D that is D, B, C, A, object. B is the first class with hi(), so it prints B.

Remember

Python searches parents left to right; check the order with Class.__mro__.

Key terms

Practice this question in Repaso