Trace Multiple Inheritance
Core idea
A class can list more than one base, as in class Scanner(Log, Device):. Python constructs one ordered sequence of classes for attribute lookup. Inspect it using Scanner.mro() (a list) or Scanner.__mro__ (a tuple). When cooperating methods use super(), the next method can belong to a sibling branch rather than the direct parent. Every participating method needs a compatible call contract.
class Local: def source(self): return "local"class Remote: def source(self): return "remote"class Reader(Local, Remote): passprint(Reader().source())For these independent bases, Local precedes Remote.
Inspect the diamond order
class Root: passclass Left(Root): passclass Right(Root): passclass Combined(Left, Right): passprint([c.__name__ for c in Combined.mro()])The common base appears once, after both branches. name gives each class name.
Continue the chain
class Root: def trace(self): return ["root"]class Left(Root): def trace(self): return ["left"] + super().trace()class Right(Root): def trace(self): return ["right"] + super().trace()class Combined(Left, Right): passprint(Combined().trace())Left delegates to Right for a Combined instance, then Right delegates to Root.
Common mistake
Directly calling both base methods can duplicate shared work in a diamond. Cooperating implementations should use super() consistently and define a clear terminating method.
Practice
Swap Left and Right in Combined. Predict and print the new MRO and trace before comparing them.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Trace multiple inheritance
Check your understanding of multiple inheritance.
What is printed?
class L: def label(self): return "left"class R: def label(self): return "right"class C(R, L): passprint(C().label())What is printed?
class A: def trace(self): return "A"class L(A): def trace(self): return "L " + super().trace()class R(A): def trace(self): return "R " + super().trace()class C(R, L): passprint(C().trace())What is printed?
class A: passclass L(A): passclass R(A): passclass C(L, R): passprint(C.mro().count(A))What supports cooperative method calls?