← Back to Python Course | Chapter 7: OOP | Lesson 5 of 11

Python Multiple Inheritance

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?

python
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)

python
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

python
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

python
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

python
class LoggingMixin:
    def log(self, message):
        print("[LOG]", message)

class Service(LoggingMixin):
    def run(self):
        self.log("Service running")

Service().run()

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.