Multiple Inheritance and Python's Object Protocol
Trace method lookup through the MRO and understand special methods.
python, inheritance, mro, super, dunderWhich method comes next?
With multiple inheritance, Python uses the method resolution order
(MRO), not a simple recursive left-to-right search of each branch.
super() continues lookup after the current class in the MRO.
Python illustration
class Base:
def label(self):
return "base"
class Left(Base):
def label(self):
return "left > " + super().label()
class Right(Base):
def label(self):
return "right > " + super().label()
class Both(Left, Right):
pass
print([cls.__name__ for cls in Both.__mro__])
print(Both().label())
Prepared output — not live execution:
['Both', 'Left', 'Right', 'Base', 'object']
left > right > base
The call first finds Left.label; super() there continues to Right,
whose super() continues to Base. Cooperative methods must agree on
their arguments and each call super() when continuation is intended.
See the reasoning
Trace method resolution
Follow cooperative calls through Both's method resolution order. This is a prepared demonstration, not live code execution.
Start at Both
- Bothno labelCurrent focus
- Leftlabel
- Rightlabel
- Baselabel
- objectend of MRO
Both has no label method, so lookup continues to Left.
Special methods
Names such as __len__, __iter__, __repr__, and __eq__ implement
Python protocols. For example, len(obj) uses the type's __len__ and
expects a non-negative integer. repr(obj) should give an informative
developer-facing representation. Equality and hashing must agree: equal
hashable objects need equal hashes. Implement only operations that make
sense for the object; special-method lookup can differ from ordinary
instance attribute lookup.
class Shelf:
def __init__(self, titles):
self.titles = list(titles)
def __len__(self):
return len(self.titles)
def __repr__(self):
return f"Shelf({self.titles!r})"
shelf = Shelf(["Read", "Write"])
print(len(shelf))
print(repr(shelf))
The prepared output is 2 and Shelf(['Read', 'Write']) on separate lines.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
