Python Multiple Inheritance
In this page:
What is Multiple Inheritance?
When a class lists more than one parent in its definition, it inherits attributes and methods from all of them simultaneously -- class Robot(Flyer, Walker): gets both fly() and walk() without either parent needing to know about the other.
Example: What is Multiple Inheritance?
class Flyer:
def fly(self):
print("Flying")
class Walker:
def walk(self):
print("Walking")
class Robot(Flyer, Walker):
pass
r = Robot()
r.fly()
r.walk()
Method Resolution Order (MRO)
MRO is the specific left-to-right, depth-first order Python searches parent classes when two or more of them define a method with the same name -- you can inspect a class's exact resolution order by calling ClassName.__mro__ or .mro().
Example: Method Resolution Order (MRO)
class A:
pass
class B(A):
pass
print(B.__mro__)
Using super() with Multiple Parents
Calling super().__init__() inside a multi-parent class's constructor doesn't just call 'the first parent' -- it follows the computed MRO chain, so with cooperative constructors each parent's __init__ runs exactly once in the correct sequence.
Example: Using super() with Multiple Parents
class A:
def __init__(self):
print("A init")
class B(A):
def __init__(self):
super().__init__()
print("B init")
B()
Resolving Name Conflicts Explicitly
When you need a specific parent's method rather than whichever one MRO would pick, you can call it directly by name -- ParentClass.method(self, ...) -- bypassing the automatic resolution order entirely, though this is normally a last resort since it can break with reordered class hierarchies.
Example: Resolving Name Conflicts Explicitly
class A:
def greet(self):
print("Hello from A")
class B:
def greet(self):
print("Hello from B")
class C(A, B):
def greet(self):
A.greet(self)
C().greet()
Mixin Classes
A mixin is a small class designed purely to be combined with others via multiple inheritance -- it typically isn't meant to be instantiated on its own (e.g. a LoggingMixin that only adds a log() method) and exists solely to add one focused capability to whatever class uses it.
Example: Mixin Classes
class LoggingMixin:
def log(self, message):
print("[LOG]", message)
class Service(LoggingMixin):
def run(self):
self.log("Service running")
Service().run()
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: