Python Multiple Inheritance, the MRO and Mixins
A class can have two parents or a whole chain of them, and one list puts them in order: the MRO. Read it, watch Python walk it, see super() follow it, and build JsonMixin and LogMixin for a User class.
What you will learn
- Tell multiple inheritance from multi-level inheritance
- Read a class's method resolution order with __mro__ and predict which method runs
- Explain why super() means the next class in the MRO, not your parent
- Write small mixins and place them on the left of the class line
Before you start
- Python inheritance, overriding and super()
So far each class has had one parent. Now a class gets two parents, or a whole chain of them. That sounds like it could get messy, and it would, except that one list explains all of it: the method resolution order, or MRO.
Two parents side by side
class Flyable:
def fly(self):
return "Flying"
class Swimmable:
def swim(self):
return "Swimming"
class Duck(Flyable, Swimmable):
pass
d = Duck()
print(d.fly())
print(d.swim())
Flying
Swimming
A duck can do both, so we write both parents in the brackets with a comma between them. That's multiple inheritance. Duck itself is only pass, yet fly comes from Flyable and swim from Swimmable. One class collects abilities from both parents.
A chain: multi-level inheritance
Multi-level is different. It's not two parents side by side, it's a chain. A GuideDog is a Dog, and a Dog is an Animal.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
def fetch(self):
return f"{self.name} fetches the ball"
class GuideDog(Dog):
def __init__(self, name, owner):
super().__init__(name)
self.owner = owner
def guide(self):
return f"{self.name} guides {self.owner}"
g = GuideDog("Rex", "Alice")
print(g.speak())
print(g.fetch())
print(g.guide())
Woof
Rex fetches the ball
Rex guides Alice
GuideDog's __init__ sends the name up with super(). Dog has no __init__, so it goes on to Animal, which stores it. For g.speak(), GuideDog has no speak, so Python goes up to Dog and prints "Woof". Animal has a speak too, but Python never gets that far. The first match wins.
The diamond
Put the two ideas together. B and C both inherit from A, and D inherits from both B and C. Draw it and you get a diamond.
class A:
def who(self):
return "A"
class B(A):
def who(self):
return "B"
class C(A):
def who(self):
return "C"
class D(B, C):
pass
print(D().who())
B
B and C each have a who. Which one runs? Python prints B. People call this the diamond problem, but Python has a fixed answer every time. What you really need is the list behind that answer.
The MRO is a list Python asks in order
Say you've lost your house key and you have a written list of people who might have a spare. You ask the first person: no. The second: no. The third says yes, so you stop right there. The last name never gets asked. Python keeps a list like that for every class.
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
print(D.__mro__)
print(D.mro() == list(D.__mro__))
print([c.__name__ for c in D.__mro__])
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
True
['D', 'B', 'C', 'A', 'object']
Read it from the left. D comes first, because Python always starts with the class itself. Then B and C, in the order D wrote them. A waits until both of its children are done, and object comes last because every class ends there. D.mro() gives the same classes as a list. When a method surprises you, print this list.
Watch Python walk the list
Now B has no who of its own; only A and C do. A class keeps its own methods in __dict__, so this loop asks each class on the list "do you yourself have who?". That's what Python does for you on every call.
class A:
def who(self):
return "A"
class B(A):
pass
class C(A):
def who(self):
return "C"
class D(B, C):
pass
for cls in D.__mro__:
found = "who" in cls.__dict__
print(cls.__name__, found)
if found:
break
print(D().who())
D False
B False
C True
C
Look at B. Its parent A does have who, but Python doesn't jump up to A. It moves to the next class on the list, C, finds it, and stops. A is never checked.
Who decides the order?
Partly, you do:
class A:
def who(self):
return "A"
class B(A):
def who(self):
return "B"
class C(A):
def who(self):
return "C"
class First(B, C):
pass
class Second(C, B):
pass
print([c.__name__ for c in First.__mro__])
print([c.__name__ for c in Second.__mro__])
print(First().who(), Second().who())
['First', 'B', 'C', 'A', 'object']
['Second', 'C', 'B', 'A', 'object']
B C
Same classes, one small swap. Two rules sit behind this: a child always comes before its parents, and parents stay in the order you wrote them.
When the rules can't both hold
class A:
pass
class B(A):
pass
class C(A, B):
pass
Traceback (most recent call last):
File "S03L04_MRO\bad_order.py", line 9, in <module>
class C(A, B):
pass
TypeError: Cannot create a consistent method resolution order (MRO) for bases A, B
We wrote A before B, so A should come first. But B is a child of A, so B must come before A. Both can't be true, so Python refuses at the class line itself, before any object exists. Swap them to class C(B, A) and it works:
class A:
pass
class B(A):
pass
class C(B, A):
pass
print([c.__name__ for c in C.__mro__])
['C', 'B', 'A', 'object']
When you see that message, check the order of the parents. A child goes before its parent.
super() follows the MRO
With several parents, super() has more to it. Every __init__ here prints its name, then calls super().__init__():
class A:
def __init__(self):
print("A.__init__")
super().__init__()
class B(A):
def __init__(self):
print("B.__init__")
super().__init__()
class C(A):
def __init__(self):
print("C.__init__")
super().__init__()
class D(B, C):
def __init__(self):
print("D.__init__")
super().__init__()
D()
print([c.__name__ for c in D.__mro__])
D.__init__
B.__init__
C.__init__
A.__init__
['D', 'B', 'C', 'A', 'object']
Look closely at B. Its parent is A, but the next class on D's list is C. So B's super() goes to C, and C's goes to A, which runs only once. The prints come out in exactly the MRO order. So super() doesn't mean "my parent". It means the next class in the MRO of the object you created.
Mixins: one small ability
Think about a plain bowl of ice cream. Mix in nuts and it gains a crunch. Mix in chocolate and it gains that too, and it's still ice cream. But a bowl of nuts on its own isn't the dessert; it's only there to be added. That's a mixin: a small class with one ability, made to be combined with another class, not used alone. By convention its name ends in Mixin.
import json
class JsonMixin:
def to_json(self):
return json.dumps(self.__dict__, indent=2)
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", "[email protected]")
u.log("Account created")
print(u.to_json())
[User] Account created
{
"name": "Alice",
"email": "[email protected]"
}
Neither mixin has an __init__. In log, self is u, so the class name gives "User". In to_json, self.__dict__ gives the object's attributes as a dictionary and json.dumps turns it into JSON text. The mixins never mention User. They work on whatever self is, so you can add them to any class.
A mixin can change a method
class Animal:
def speak(self):
return "hello"
class ShoutMixin:
def speak(self):
return super().speak().upper() + "!"
class Dog(ShoutMixin, Animal):
pass
print(Dog().speak())
print([c.__name__ for c in Dog.__mro__])
HELLO!
['Dog', 'ShoutMixin', 'Animal', 'object']
ShoutMixin calls super() even though it has no parent of its own. On a Dog, the next class after ShoutMixin in the MRO is Animal, so "hello" comes back and the mixin shouts it. That's why a mixin goes on the left: it gets the first turn, and super() hands over to the main class. Put it on the right and Animal's speak is found first, so the mixin never runs.
Habits that keep this readable
- Keep a mixin small: one ability, and a name ending in
Mixin. - Try not to give a mixin its own
__init__. Let it use what the class already has. - Mixins on the left, the main class on the right.
- Keep the chain short. A couple of levels is easy to follow; a tall one isn't.
- When an AI tool writes you a class with several parents, print its MRO and read that list before you trust the code.
If this is your first time with super(), start with inheritance and polymorphism.
Try it yourself
Write a mixin with one method, add it to User, and print the MRO. Or prompt an AI tool to write it, then read every line it gives you.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Class Methods, Static Methods and Properties: What Each One Receives
Instance methods get self, class methods get cls, static methods get nothing. Then properties, setters and deleters, with small runnable files and their real output.
Python Classes and Objects: __init__, self and PEP 8 Names
A class is the blueprint and an object is what you build from it. Car, Student, Dog, Circle and BankAccount show what __init__ and self really do, how attribute lookup works, the missing self error, and PEP 8 names.
Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
A child class gets everything from its parent, Python walks up and stops at the first match, and super() reaches the parent. Then polymorphism: one call, a different method for each object, with Animal, Employee and Shape examples and their real output.
Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
Python has no private keyword: one underscore is a sign, two underscores is a rename, and nothing is locked. Then the dunder methods that let print, ==, +, len, [] and for work on your own Book, Song, Vector and Playlist objects.
