Lesson · Object-Oriented Python
Multiple Inheritance & MRO
70 min readMultiple Inheritance & MRO
Multiple inheritance uses a deterministic method resolution order based on C3 linearization. `super()` follows that MRO, which is why cooperative classes can compose cleanly and non-cooperative classes can break diamonds.
Learning goals
- Read
class D(B, C)and write its MRO by hand:D, B, C, A, object. - Explain why
B.run'ssuper().run()reachesC.runand notA.run. - Predict the print order of
D().run()once the chain has a terminal base, and whyA.runraisesAttributeErrorwithout one. - Use
D.__mro__to check an ordering instead of guessing from the class statements. - Describe what the diamond problem is and how one linearized order solves it.
Mental model
The arrows follow the MRO, not the class statements: after B the chain visits C because C sits next in the linearization, even though B's only direct base is A. Giving the chain a terminal class whose run does not call super() is what stops it.
One ordered list, walked by super()
the diamond is flattened, not visited twice
Mental model
the same mechanism as a compact list
D.__mro__ = (D, B, C, A, object)
D().run() → D.run → super().run() →
B.run → super().run() →
C.run → super().run() →
A.run → super().run() → object has no run → AttributeErrorCore idea
Multiple inheritance works because Python computes one linear order, the MRO, that satisfies every class's local ordering while keeping each ancestor reachable; __mro__ shows the result and super() walks it. The diamond problem disappears in this design: a shared ancestor appears once, at the position the linearization chooses. Cooperative classes are the ones whose methods accept the same call shape and pass control along the chain with super(), which is what keeps the order meaningful.
Multiple inheritance
Multiple inheritance lets a class name more than one base, as in class D(B, C). Python merges the bases into a single MRO so attribute lookup stays deterministic: every search walks one ordered list of classes. Use it for narrow mixins with compatible interfaces, since each extra base adds its whole public surface to the subclass.
Method Resolution Order
The MRO defines the order in which Python searches classes for attributes. Multiple inheritance uses C3 linearization to produce an order that respects local parent ordering and monotonicity.
C3 linearization intuition
C3 linearization is the rule that builds the MRO by merging the bases' MROs while preserving each class's local order and keeping a class before its parents. The practical intuition is that a subclass always precedes its bases, and the leftmost base's chain is preferred when there is no conflict. When no consistent order exists, Python refuses to create the class with a TypeError about an inconsistent MRO.
Class.__mro__
Class.__mro__ is the tuple of classes Python searches, in order, for attributes of that class; it starts with the class itself and ends with object. Printing it is the fastest way to settle an argument about which definition wins, because the first matching entry is the one that runs. Class.mro() returns the same order as a list computed at class-creation time.
Cooperative super()
Cooperative super() means every method in the chain passes control to the next class with super().method(...) instead of calling a specific parent. The zero-argument form uses the current class to find its place in the MRO and resumes the search right after it. This is what lets several bases share one call without knowing about each other, provided their signatures match.
Diamond inheritance
A diamond occurs when multiple inheritance paths share a common ancestor. Python's MRO ensures that ancestor is reached in a consistent order rather than naively once per path.
Walkthrough
class D(B, C)asks C3 to merge the MROs ofBandC; the result is(D, B, C, A, object), whichprint(D.__mro__)shows directly.- Each
runprints its letter and then callssuper().run(), so control moves to the next class in that tuple; insideB.runthe next class isC, not the direct baseA. - The chain in the listing has no terminal:
A.run'ssuper().run()reachesobject, which defines norun, so actually callingD().run()printsD, B, C, Aand then raisesAttributeError. TheEndclass shows the intended fix, a class whoserunsimply stops. - Predict before running: the exact tuple
print(D.__mro__)shows, the print order ofD().run()once a terminal class ends the chain, and the line that raises without one.
Experiments to try
- Make the chain complete by giving
Aa terminal base (class A(End):), runD().run(), and check that the print order matchesD.__mro__minusobject. - Remove
super().run()fromC.runand run again; note thatA.runnever executes and say what the chain lost. - Reverse the bases to
class D(C, B)and print the new MRO; explain which ofB.runandC.runnow runs second. - Move the
printinB.runafter itssuper().run()and describe how the output order changes, connecting it to where the recursive call sits.
Playable lesson
Lab: MRO explorer
Build a class graph interactively and display the computed MRO. Step through each super() call along the lookup path.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
MRO explorer
Class graph
D.__mro__ (search order)
Output
D().run() has not run yet
The MRO is the single ordered list Python searches. `super()` resumes at the next entry, so each method in the chain runs exactly once.
Predict first
For `class D(B, C)`, `super().run()` inside `B.run` continues to which class?
Predict first
What does `print(D.__mro__)` show for `class D(B, C)` with both B and C extending A?
Predict first
Does `super()` always mean the direct parent class?
Common mistakes
- Calling a parent directly, as in
A.run(self), inside a cooperative chain: the jump skips every class between the current one andAin the MRO, so those methods silently stop running. - Assuming
super()means "my parent": insideclass D(B, C),super()inBcontinues toC, not toA, which is why an incompatible class in the middle changes the output. - Combining bases whose method signatures disagree:
super().run()raisesTypeErrorwhen the next method in the MRO cannot accept the arguments the current call supplies. - Letting one class on the chain stop calling
super(): the call truncates there, and every class after it in the MRO is skipped even though the code contains methods for them.
Practice: Easy
- Write the tuple for
D.__mro__by hand before runningprint(D.__mro__); explain whyAappears once even though two paths lead to it. - Call
D().run()exactly as listed and record the point where it raises; then wire the terminal withclass A(End):and record the full print order. - Swap the bases to
class D(C, B)and record the new MRO; state which ofB.runandC.runruns first and why.
Practice: Medium
- Give
End.runa print of"End"and run the completed chain; check that the output order matchesD.__mro__element for element. - Add a
stop(self)method that onlyAdefines, call it on aDinstance, and explain how lookup finds it through the MRO even thoughBandCdo not define it. - Make
Cnon-cooperative by deleting itssuper().run()call and list which classes afterCin the MRO stop running; name the mechanism that causes it.
Practice: Hard
- Design a
Logger,Cache, andServicemixin set whereService(Logger, Cache)cooperates: everyhandlecallssuper().handle(...). Define the MRO, the terminal base, and tests pinning the call order before implementing. - Build a failure lab: a diamond without a terminal base, a class that skips
super(), and two bases whose method signatures disagree. Show each error or silent truncation, then fix each with the smallest change. - Connect this lesson to the composition lesson: take the diamond and replace one branch with a contained collaborator object, then argue when composition beats multiple inheritance for the same behavior.
Lesson checklist
- I can write the MRO of
D(B, C)with a shared baseAby hand. - I can explain why
B.run'ssuper().run()lands onC.run. - I can say what a terminal base class is and why the listing's chain needs one.
- I can point at
D.__mro__to check an ordering instead of guessing.
Remember
C3 linearization turns several bases into one deterministic search order, printed by `__mro__`, and `super()` walks that order rather than the class statement. A diamond therefore visits the shared ancestor once, and the design only works when every method on the chain cooperates: same signature, always passing control to the next entry, with a terminal base to stop.
Interview angles
What is the main purpose of **Multiple inheritance**?+
Multiple inheritance lets a class name more than one base, as in class D(B, C). Python merges the bases into a single MRO so attribute lookup stays deterministic: every search walks one ordered list of classes. Use it for narrow mixins with compatible interfaces, since each extra base adds its whole public surface to the subclass.
What should you pay attention to when using **Method Resolution Order**?+
The MRO defines the order in which Python searches classes for attributes. Multiple inheritance uses C3 linearization to produce an order that respects local parent ordering and monotonicity.
How does **C3 linearization intuition** fit into this lesson?+
C3 linearization is the rule that builds the MRO by merging the bases' MROs while preserving each class's local order and keeping a class before its parents. The practical intuition is that a subclass always precedes its bases, and the leftmost base's chain is preferred when there is no conflict. When no consistent order exists, Python refuses to create the class with a TypeError about an inconsistent MRO.
Why can calling `A.run(self)` inside a cooperative chain be worse than calling `super().run()`?+
A direct call jumps to one fixed class every time, so classes between the current class and A in the MRO are skipped and never run; the chain silently loses its middle steps. super().run() resumes at the next class in the MRO, which is what keeps the whole chain alive.