Skip to main content
Editor

Python Multiple Inheritance and MRO: How It Actually Works

Advanced25 min5 exercises95 XP
0/5 exercises

Think about how you inherit traits from your parents. You might have your mom's eyes and your dad's sense of humor. You didn't pick one parent - you got traits from both.

Python classes can do the same thing. A class can inherit from two or more parent classes at once, combining their abilities. This is called multiple inheritance, and Python is one of the few popular languages that supports it directly.

Multiple inheritance is powerful, but it introduces a tricky question: if two parents define the same method, which one wins? In this tutorial, you'll learn how Python answers that question using the Method Resolution Order (MRO), how to avoid the famous diamond problem, and how to use mixins to keep things clean.

How Does Basic Multiple Inheritance Work?

To inherit from multiple classes, list them all inside the parentheses separated by commas. The child class gets every method and attribute from all of its parents.

A class with two parents
class Flyer:
def fly(self):
return 'I can fly!'
class Swimmer:
def swim(self):
return 'I can swim!'
class Duck(Flyer, Swimmer):
def quack(self):
return 'Quack!'
donald = Duck()
print(donald.fly())
print(donald.swim())
print(donald.quack())
Output
I can fly!
I can swim!
Quack!

The Duck class didn't define fly() or swim(), but it can use both because it inherits from Flyer and Swimmer. Each parent contributes its own methods, and the child gets them all.

isinstance() with multiple parents
class Flyer:
def fly(self):
return 'I can fly!'
class Swimmer:
def swim(self):
return 'I can swim!'
class Duck(Flyer, Swimmer):
pass
d = Duck()
print(isinstance(d, Flyer))
print(isinstance(d, Swimmer))
print(isinstance(d, Duck))
Output
True
True
True

What Is the Diamond Problem?

The diamond problem happens when a class inherits from two parents that share the same grandparent. If you draw the inheritance tree, it looks like a diamond shape.

Here's the situation: class A defines a method. Classes B and C both inherit from A. Then class D inherits from both B and C. When D calls that method, which version does it get - B's or C's?

The diamond problem
class A:
def greet(self):
return 'Hello from A'
class B(A):
def greet(self):
return 'Hello from B'
class C(A):
def greet(self):
return 'Hello from C'
class D(B, C):
pass
d = D()
print(d.greet())
Output
Hello from B

Python picks B's version because B is listed first in the class definition: class D(B, C). But the full story is more interesting than just "first wins." Python uses an algorithm called C3 linearization to decide the exact order.


How Does Python Decide Which Method to Call? (MRO)

The Method Resolution Order (MRO) is the exact sequence Python follows when looking up a method. It's like a search order: Python checks class D first, then B, then C, then A, then object. The first match wins.

You can see any class's MRO by calling the .__mro__ attribute or the mro() method.

Inspecting the MRO
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
for cls in D.__mro__:
print(cls.__name__)
Output
D
B
C
A
object

The order is D -> B -> C -> A -> object. Python uses the C3 linearization algorithm to compute this. The key rules are: children come before parents, and the left-to-right order from the class definition is preserved.

When MRO fails: inconsistent ordering
class X:
pass
class Y:
pass
class A(X, Y):
pass
class B(Y, X):
pass
# This creates a contradiction: A says X before Y, B says Y before X
try:
class C(A, B):
pass
except TypeError as e:
print(f'MRO Error: {e}')
Output
MRO Error: Cannot create a consistent method resolution order (MRO) for bases X, Y

How Does super() Work with Multiple Inheritance?

Here's where it gets really interesting. super() doesn't just call the parent class - it calls the next class in the MRO. This means super() inside B might call C instead of A, depending on the actual object's MRO.

super() follows the MRO chain
class A:
def greet(self):
print('A says hello')
class B(A):
def greet(self):
print('B says hello')
super().greet()
class C(A):
def greet(self):
print('C says hello')
super().greet()
class D(B, C):
def greet(self):
print('D says hello')
super().greet()
print('MRO:', [cls.__name__ for cls in D.__mro__])
print()
d = D()
d.greet()
Output
MRO: ['D', 'B', 'C', 'A', 'object']

D says hello
B says hello
C says hello
A says hello

Notice the order: D calls B (next in MRO), B calls C (not A!), C calls A, and A has no super call to make. Each class in the MRO gets called exactly once. This is called cooperative multiple inheritance.

Cooperative __init__ with **kwargs
class Base:
def __init__(self, **kwargs):
# Absorb remaining kwargs at the end of the MRO
pass
class Named(Base):
def __init__(self, name='', **kwargs):
super().__init__(**kwargs)
self.name = name
class Aged(Base):
def __init__(self, age=0, **kwargs):
super().__init__(**kwargs)
self.age = age
class Person(Named, Aged):
pass
p = Person(name='Alice', age=30)
print(f'{p.name}, age {p.age}')
Output
Alice, age 30

The **kwargs pattern is the standard way to make __init__ cooperative. Each class takes what it needs and passes the rest up the chain. The Base class at the end absorbs any leftover keyword arguments.


What Are Mixins and Why Should You Use Them?

A mixin is a small class designed to add a specific feature to other classes. It's not meant to stand on its own - it's a building block you snap onto existing classes. Think of it like a phone case with a built-in wallet. The case isn't a phone, but it adds wallet functionality to any phone.

By convention, mixin class names end with Mixin. This makes their purpose immediately clear to anyone reading the code.

Practical mixins
class JsonMixin:
def to_json(self):
import json
return json.dumps(self.__dict__)
class LogMixin:
def log(self, message):
print(f'[{self.__class__.__name__}] {message}')
class User(JsonMixin, LogMixin):
def __init__(self, name, email):
self.name = name
self.email = email
u = User('Alice', 'alice@example.com')
print(u.to_json())
u.log('User created')
Output
{"name": "Alice", "email": "alice@example.com"}
[User] User created

Mixins are the most practical use of multiple inheritance. Instead of building deep, complex hierarchies, you compose classes from small, reusable pieces. This approach is easier to test, understand, and maintain.

Composing multiple mixins
class ValidatorMixin:
def validate(self):
for attr, value in self.__dict__.items():
if value is None:
raise ValueError(f'{attr} cannot be None')
return True
class RepresentableMixin:
def display(self):
fields = ', '.join(f'{k}={v!r}' for k, v in self.__dict__.items())
return f'{self.__class__.__name__}({fields})'
class Order(ValidatorMixin, RepresentableMixin):
def __init__(self, item, quantity, price):
self.item = item
self.quantity = quantity
self.price = price
order = Order('Widget', 10, 4.99)
print(order.display())
print(f'Valid: {order.validate()}')
Output
Order(item='Widget', quantity=10, price=4.99)
Valid: True

A common real-world pattern is combining a main base class with utility mixins. For example, a web framework might let you write class MyView(LoginRequiredMixin, ListView) - one mixin for authentication and one base class for the page type.

When listing parents, put mixins first and the main base class last. This ensures mixin methods take priority over base class defaults, and the MRO stays predictable.


Practice Exercises

Create a Hybrid Class
Write Code

Create three classes:

  • Runner with a method run() that returns 'Running fast'
  • Climber with a method climb() that returns 'Climbing high'
  • Adventurer that inherits from both Runner and Climber and adds a method describe() that returns 'I can run and climb'
  • Create an Adventurer instance and print all three methods.

    # Create Runner, Climber, and Adventurer classes
    Predict the MRO
    Predict Output

    What does this code print? Think about the Method Resolution Order.

    class A:
        def who(self):
            return 'A'
    
    class B(A):
        pass
    
    class C(A):
        def who(self):
            return 'C'
    
    class D(B, C):
        pass
    
    d = D()
    print(d.who())

    Remember: Python follows the MRO, not just the direct parent.

    # What does d.who() return?
    # Type your prediction as a print statement:
    print('C')
    Fix the Cooperative __init__
    Fix the Bug

    This code uses multiple inheritance but the __init__ methods don't cooperate properly. Fix it so the output is:

    Alice, age 25

    Hint: use **kwargs to pass remaining arguments up the MRO chain.

    class Base:
    def __init__(self):
    pass
    class Named(Base):
    def __init__(self, name):
    self.name = name
    class Aged(Base):
    def __init__(self, age):
    self.age = age
    class Person(Named, Aged):
    pass
    p = Person(name='Alice', age=25)
    print(f'{p.name}, age {p.age}')
    Build a TimestampMixin
    Write Code

    Create a TimestampMixin class with a method created_info() that returns the string 'Created by <class_name>' where <class_name> is the actual class name. Then create a Document class that inherits from TimestampMixin and has an __init__ that takes a title. Print the title and the created_info().

    Expected output:

    My Report
    Created by Document
    # Create TimestampMixin and Document
    Predict the super() Chain
    Predict Output

    What does this code print? Trace through the super() calls following the MRO.

    class Base:
        def show(self):
            print('Base')
    
    class Left(Base):
        def show(self):
            print('Left')
            super().show()
    
    class Right(Base):
        def show(self):
            print('Right')
            super().show()
    
    class Child(Left, Right):
        def show(self):
            print('Child')
            super().show()
    
    Child().show()
    # What gets printed? Write your prediction:
    print('Child')
    print('Left')
    print('Right')
    print('Base')

    Harder problems

    More problems on this topic: Classes

    Related Tutorials

    Was this tutorial helpful?