Mixins & Multiple Inheritance

Published by Brayan K

Learn the REAL Python OOP system used by Django, FastAPI, SQLAlchemy, Pydantic, PyTorch, and Scrapy. Master mixins, multiple inheritance, and professional OOP patterns used in large-scale frameworks.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Several parents: the order Python searches them

Inheritance and Polymorphism closed with a Duck that had two parents, and left two questions for this lesson: in what order Python searches several parents, and what super() means then. After those come mixins, small classes that add one ability to many others, and when to hold an object instead of inheriting from it.

The examples are plain classes and the standard library's own mixins, which run anywhere. The frameworks work the same way: Django's LoginRequiredMixin, for one, ends its dispatch() with a super() call, as the mixins here do. Named patterns such as Strategy and Factory are in Design Patterns in Python (Singleton, Factory, Strategy).

When two parents share a parent of their own, Python doesn't search depth-first. Copier's parents are Printer and Scanner, both built on Device. Printer has no describe(), so a search that went all the way up Printer's side first would reach Device and say "a device":

class Device:
    def describe(self):
        return "a device"

class Printer(Device):
    pass

class Scanner(Device):
    def describe(self):
        return "a scanner"

class Copier(Printer, Scanner):
    pass

print(Copier().describe())
print([cls.__name__ for cls in Copier.__mro__])

# ✅ Expected output:
# a scanner
# ['Copier', 'Printer', 'Scanner', 'Device', 'object']

The order Python searches is the class's MRO, short for method resolution order, which __mro__ holds and mro() returns as a list. It keeps each class line's order, left to right, and puts every class before its own parents, so a parent that two classes share comes after both of them. Python works the order out, with an algorithm called C3 linearization, when it makes the class.

A class line that can't be put in such an order is refused there and then. Listing the same parent twice is the simplest case:

class Walker:
    pass

class Robot(Walker, Walker):
    pass

# ✅ Expected error:
# TypeError: duplicate base class Walker

The other case is two class lines that disagree. With Duck(Walker, Swimmer) and Penguin(Swimmer, Walker), class Odd(Duck, Penguin) would need Walker both before and after Swimmer, so it stops with TypeError: Cannot create a consistent method resolution order (MRO) for bases Walker, Swimmer. Python 3.10 to 3.12 break that message after "resolution", so its last line there is order (MRO) for bases Walker, Swimmer.

super() calls the next class in the MRO

With one parent, super() reaches the parent. With several, it reaches the next class in the MRO of the object the method is running for. The same super().start() line in Printer goes to Scanner for a Copier, and to Device for a Printer:

class Device:
    def start(self):
        print("Device.start")

class Printer(Device):
    def start(self):
        print("Printer.start")
        super().start()

class Scanner(Device):
    def start(self):
        print("Scanner.start")
        super().start()

class Copier(Printer, Scanner):
    pass

Copier().start()
print("---")
Printer().start()

# ✅ Expected output:
# Printer.start
# Scanner.start
# Device.start
# ---
# Printer.start
# Device.start

Printer's only parent is Device, yet for a Copier its super() went to Scanner. That's what lets every class in the chain do its part once. Call the parents by name instead, and the part they share runs twice:

class Device:
    def __init__(self):
        print("Device set up")

class Printer(Device):
    def __init__(self):
        Device.__init__(self)
        print("Printer set up")

class Scanner(Device):
    def __init__(self):
        Device.__init__(self)
        print("Scanner set up")

class Copier(Printer, Scanner):
    def __init__(self):
        Printer.__init__(self)
        Scanner.__init__(self)

Copier()

# ✅ Expected output:
# Device set up
# Printer set up
# Device set up
# Scanner set up

With super() in every __init__, each one runs once, in MRO order. Each class calls super() before its own print(), so the lines come out from the far end of the MRO back:

class Device:
    def __init__(self):
        print("Device set up")

class Printer(Device):
    def __init__(self):
        super().__init__()
        print("Printer set up")

class Scanner(Device):
    def __init__(self):
        super().__init__()
        print("Scanner set up")

class Copier(Printer, Scanner):
    def __init__(self):
        super().__init__()
        print("Copier set up")

Copier()

# ✅ Expected output:
# Device set up
# Scanner set up
# Printer set up
# Copier set up

That's why a class that may end up with several parents should use super(), and not name its parent: it can't know which class will come next.

Mixins: one ability, added from the left

A mixin is a class written to be one of several parents. It adds one ability, works only through self, and isn't meant to be used on its own. This LoggingMixin adds a line before whatever save() comes after it in the MRO:

class BaseModel:
    def save(self):
        print("saved to the database")

class LoggingMixin:
    def save(self):
        print("logging the save")
        super().save()

class User(LoggingMixin, BaseModel):
    pass

User().save()
print([cls.__name__ for cls in User.__mro__])

# ✅ Expected output:
# logging the save
# saved to the database
# ['User', 'LoggingMixin', 'BaseModel', 'object']

Listed on the other side, the mixin never runs, and there's no error to say so. BaseModel's save() comes first and doesn't call super(), so the search ends there:

class BaseModel:
    def save(self):
        print("saved to the database")

class LoggingMixin:
    def save(self):
        print("logging the save")
        super().save()

class User(BaseModel, LoggingMixin):
    pass

User().save()
print([cls.__name__ for cls in User.__mro__])

# ✅ Expected output:
# saved to the database
# ['User', 'BaseModel', 'LoggingMixin', 'object']

So a mixin goes to the left of the class it changes. The standard library's own notes say so: the socketserver module's documentation says "The Mix-in class must come first", and http.server builds its threading web server that way. Printing its MRO starts no server:

from http.server import ThreadingHTTPServer

print([cls.__name__ for cls in ThreadingHTTPServer.__mro__])
print(ThreadingHTTPServer.__bases__[0].__module__)

# ✅ Expected output:
# ['ThreadingHTTPServer', 'ThreadingMixIn', 'HTTPServer', 'TCPServer', 'BaseServer', 'object']
# socketserver

Something after the mixin must also have the method its super() call asks for. Used on its own, a mixin's super() reaches object, which has no save():

class LoggingMixin:
    def save(self):
        print("logging the save")
        super().save()

class Note(LoggingMixin):
    pass

Note().save()

# ✅ Expected output:
# logging the save

# ✅ Expected error:
# AttributeError: 'super' object has no attribute 'save'

The other way round, the class at the far end of the chain, here BaseModel, must not call super() for that method, or it fails the same way after everything else has run.

__init__ in a chain: take keywords, pass the rest on

Each __init__ in a chain is called by the one before it, and can't know what the next one needs. So each takes its own arguments by keyword, after a *, and passes everything else on with **kwargs, the forwarding from *args & **kwargs:

class Named:
    def __init__(self, *, name, **kwargs):
        super().__init__(**kwargs)
        self.name = name

class Coloured:
    def __init__(self, *, colour="black", **kwargs):
        super().__init__(**kwargs)
        self.colour = colour

class Pen(Named, Coloured):
    pass

pen = Pen(name="biro", colour="blue")
print(pen.name, pen.colour)
pencil = Pen(name="pencil")
print(pencil.name, pencil.colour)

# ✅ Expected output:
# biro blue
# pencil black

With positional parameters, each super().__init__() call would have to guess what the next class wants, and it can't. Named's call gives Coloured no colour:

class Named:
    def __init__(self, name):
        super().__init__()
        self.name = name

class Coloured:
    def __init__(self, colour):
        super().__init__()
        self.colour = colour

class Pen(Named, Coloured):
    pass

Pen("biro")

# ✅ Expected error:
# TypeError: Coloured.__init__() missing 1 required positional argument: 'colour'

A misspelt keyword is passed along the whole chain to object, whose message doesn't name it:

class Named:
    def __init__(self, *, name, **kwargs):
        super().__init__(**kwargs)
        self.name = name

class Coloured:
    def __init__(self, *, colour="black", **kwargs):
        super().__init__(**kwargs)
        self.colour = colour

class Pen(Named, Coloured):
    pass

Pen(name="biro", color="blue")

# ✅ Expected error:
# TypeError: object.__init__() takes exactly one argument (the instance to initialize)

So a mixin can have an __init__, as long as it takes keywords and calls super().__init__(**kwargs), and every class before it in the MRO does the same. One __init__ that doesn't call super() ends the chain there.

A list or dict in a mixin's class body is shared

Object-Oriented Programming showed one list for every dog: a list made in the class body belongs to the class, and every object shares it. In a mixin, it's one for every class built on the mixin as well:

class CacheMixin:
    _cache = {}

    def remember(self, key, value):
        self._cache[key] = value

    def recall(self, key):
        return self._cache.get(key)

class WeatherClient(CacheMixin):
    pass

class StockClient(CacheMixin):
    pass

WeatherClient().remember("today", "rain")
print(StockClient().recall("today"))
print(WeatherClient._cache is StockClient._cache)

# ✅ Expected output:
# rain
# True

A cooperative __init__ gives each object a dict of its own:

class CacheMixin:
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._cache = {}

    def remember(self, key, value):
        self._cache[key] = value

    def recall(self, key):
        return self._cache.get(key)

class WeatherClient(CacheMixin):
    pass

class StockClient(CacheMixin):
    pass

weather = WeatherClient()
weather.remember("today", "rain")
print(StockClient().recall("today"), weather.recall("today"))

# ✅ Expected output:
# None rain

Inherit, mix in, or hold an object

Inheritance and Polymorphism gave a Car an Engine to hold rather than making it inherit from one, and called that composition. Here is what the choice changes. Built on list, a Stack gets every list method, and two of them break peek(): blue was pushed last, yet peek() says red:

class Stack(list):
    def push(self, item):
        self.append(item)

    def peek(self):
        return self[-1]

plates = Stack()
plates.push("red")
plates.push("blue")
plates.insert(0, "green")
plates.sort()
print(plates.peek())
print(plates)

# ✅ Expected output:
# red
# ['blue', 'green', 'red']

Holding a list instead, the Stack offers only the methods it defines:

class Stack:
    def __init__(self):
        self._items = []

    def push(self, item):
        self._items.append(item)

    def pop(self):
        return self._items.pop()

    def peek(self):
        return self._items[-1]

plates = Stack()
plates.push("red")
plates.push("blue")
print(plates.peek())
plates.insert(0, "green")

# ✅ Expected output:
# blue

# ✅ Expected error:
# AttributeError: 'Stack' object has no attribute 'insert'

A part you hold can be replaced on one object while the program runs, without changing the class's inheritance structure:

class EmailNotifier:
    def notify(self, text):
        return "email: " + text

class TextNotifier:
    def notify(self, text):
        return "text: " + text[:12]

class Order:
    def __init__(self, item, notifier):
        self.item = item
        self.notifier = notifier

    def ship(self):
        print(self.notifier.notify(f"your {self.item} has shipped"))

order = Order("tea", EmailNotifier())
order.ship()
order.notifier = TextNotifier()
order.ship()

# ✅ Expected output:
# email: your tea has shipped
# text: your tea has

Swapping a part like this is the Strategy pattern in Design Patterns in Python (Singleton, Factory, Strategy). To choose between the three:

Methods the standard library mixes in for you

collections.abc.Mapping works like a large mixin. A class that writes __getitem__, __iter__ and __len__, the methods from Magic Methods & the Python Data Model, gets get(), in, keys(), items() and == from it:

from collections.abc import Mapping

class Prices(Mapping):
    def __init__(self, data):
        self._data = {k.lower(): v for k, v in data.items()}

    def __getitem__(self, key):
        return self._data[key.lower()]

    def __iter__(self):
        return iter(self._data)

    def __len__(self):
        return len(self._data)

prices = Prices({"Tea": 3, "Milk": 1})
print(prices["TEA"], prices.get("coffee", 0), "MILK" in prices)
print(list(prices.items()))

# ✅ Expected output:
# 3 0 True
# [('tea', 3), ('milk', 1)]

Leave one of the three out, and Python refuses to make a Prices at all. Abstract Base Classes (abc) covers classes like Mapping, and how to write your own.

Practice: a report with a title and numbered lines

Two mixins change a report's lines: one numbers them, the other adds a title. Fill in what each mixin's lines() calls to get the lines from the rest of the chain, and the mixin missing from the class line. The comment at the end of a line holds its blank's answer, if you want to check.

class Report:
    def lines(self, rows):
        return list(rows)

class NumberedMixin:
    def lines(self, rows):
        rows = ___.lines(rows)                  # 👉 replace ___ with super()
        return [f"{n}. {row}" for n, row in enumerate(rows, 1)]

class TitleMixin:
    def lines(self, rows):
        return ["Scores"] + ___.lines(rows)     # 👉 replace ___ with super()

class ScoreReport(TitleMixin, ___, Report):     # 👉 replace ___ with NumberedMixin
    pass

for line in ScoreReport().lines(["Ada 91", "Ben 78"]):
    print(line)
print([cls.__name__ for cls in ScoreReport.__mro__])

# ✅ Expected output:
# Scores
# 1. Ada 91
# 2. Ben 78
# ['ScoreReport', 'TitleMixin', 'NumberedMixin', 'Report', 'object']

Here the order matters. With NumberedMixin first, class ScoreReport(NumberedMixin, TitleMixin, Report), the title is numbered too, 1. Scores, because NumberedMixin then numbers the lines TitleMixin returns.

On your own: products that turn into JSON

Write three mixins and a class built on all of them. ToDictMixin.to_dict() returns a copy of the object's attributes, which vars(self) holds. JSONMixin.to_json() returns json.dumps(self.to_dict(), sort_keys=True), using a method it doesn't define itself. TaggedMixin has an __init__ that takes tags by keyword, with an empty default, stores them as a list and passes everything else on. Product takes name and pence by keyword. If tea's JSON comes out with no "tags" at all and nothing fails, Product's __init__ isn't calling super().__init__(**kwargs).

# your code here

tea = Product(name="tea", pence=120, tags=["hot", "drink"])
milk = Product(name="milk", pence=90)
print(tea.to_json())
print(milk.to_json())
print([cls.__name__ for cls in Product.__mro__])
import json

class ToDictMixin:
    def to_dict(self):
        return dict(vars(self))

class JSONMixin:
    def to_json(self):
        return json.dumps(self.to_dict(), sort_keys=True)

class TaggedMixin:
    def __init__(self, *, tags=(), **kwargs):
        super().__init__(**kwargs)
        self.tags = list(tags)

class Product(JSONMixin, ToDictMixin, TaggedMixin):
    def __init__(self, *, name, pence, **kwargs):
        super().__init__(**kwargs)
        self.name = name
        self.pence = pence

tea = Product(name="tea", pence=120, tags=["hot", "drink"])
milk = Product(name="milk", pence=90)
print(tea.to_json())
print(milk.to_json())
print([cls.__name__ for cls in Product.__mro__])

# ✅ Expected output:
# {"name": "tea", "pence": 120, "tags": ["hot", "drink"]}
# {"name": "milk", "pence": 90, "tags": []}
# ['Product', 'JSONMixin', 'ToDictMixin', 'TaggedMixin', 'object']

list(tags) gives each product a list of its own, so changing one product's tags can't change another's. The default, an empty tuple, can't be changed at all.

Practice quiz

class A: pass, class B(A): pass, class C(A): pass and class D(C, B): pass. What does print([k.__name__ for k in D.__mro__]) print?

  • ['D', 'C', 'A', 'B', 'object']
  • ['D', 'B', 'C', 'A', 'object']
  • It stops with TypeError: duplicate base class A
  • ['D', 'C', 'B', 'A', 'object']

Answer: ['D', 'C', 'B', 'A', 'object']. The MRO keeps the class line's order, C before B, and puts every class before its own parents, so A, which both of them build on, comes after both.

Device's start() prints Device.start. Printer and Scanner, both built on Device, each print their own name and then call super().start(). With class Copier(Scanner, Printer): pass, what does Copier().start() print?

  • Scanner.start, Device.start
  • Scanner.start, Printer.start, Device.start
  • Printer.start, Scanner.start, Device.start
  • Scanner.start, Device.start, Printer.start, Device.start

Answer: Scanner.start, Printer.start, Device.start. Copier's MRO is Copier, Scanner, Printer, Device, object. Scanner's super() goes to the next class in it, Printer, and Printer's to Device.

Printer and Scanner, both built on Device, call super().__init__() and then print their own "set up" line. Copier(Printer, Scanner) has an __init__ that calls Printer.__init__(self) and then Scanner.__init__(self). How many times does Copier() print "Scanner set up"?

  • Once
  • Never
  • Twice
  • Three times

Answer: Twice. Printer.__init__ runs for a Copier, so its super() goes to the next class in Copier's MRO, which is Scanner. Then Copier calls Scanner.__init__ by name as well.

LoggingMixin's save() prints "logged" and then calls super().save(). BaseModel's save() prints "saved" and then calls super().save() too. What does User().save() do, for class User(LoggingMixin, BaseModel)?

  • It prints logged and saved, then stops with AttributeError: 'super' object has no attribute 'save'
  • It prints logged, then saved
  • It prints saved, then logged
  • It stops with AttributeError before printing anything

Answer: It prints logged and saved, then stops with AttributeError: 'super' object has no attribute 'save'. BaseModel is the last class with a save(), so its super() reaches object, which has none. The class at the end of the chain mustn't call super() for that method.

Named takes name by keyword, Coloured takes colour by keyword with a default of "black", and both pass the rest on with super().__init__(**kwargs). What does Pen(name="biro", size=3) do, for class Pen(Named, Coloured)?

  • It makes a black pen and ignores size
  • It stops with TypeError: Pen.__init__() got an unexpected keyword argument 'size'
  • It stops with TypeError: Coloured.__init__() got an unexpected keyword argument 'size'
  • It stops with TypeError: object.__init__() takes exactly one argument (the instance to initialize)

Answer: It stops with TypeError: object.__init__() takes exactly one argument (the instance to initialize). Nobody takes size, so each class passes it on, and object.__init__ gets it at the end of the chain.

Named's __init__(self, name) and Coloured's __init__(self, colour) each call super().__init__() with no arguments. What does Pen("biro", "blue") do, for class Pen(Named, Coloured)?

  • It makes a pen named biro, coloured blue
  • It stops with TypeError: Coloured.__init__() missing 1 required positional argument: 'colour'
  • It stops with TypeError: Named.__init__() takes 2 positional arguments but 3 were given
  • It makes a pen named biro and ignores blue

Answer: It stops with TypeError: Named.__init__() takes 2 positional arguments but 3 were given. Pen has no __init__ of its own, so Python calls the first one in the MRO, Named's, with both values, and Named takes only one.

Tool's __init__(self, name) stores the name and doesn't call super(). DebugMixin's __init__(self, *args, **kwargs) calls super().__init__(*args, **kwargs) and sets self.debug = True. What does print(Hammer("hammer").debug) do, for class Hammer(Tool, DebugMixin)?

  • It prints True
  • It stops with AttributeError: 'Hammer' object has no attribute 'debug'
  • It stops with TypeError
  • It prints None

Answer: It stops with AttributeError: 'Hammer' object has no attribute 'debug'. Tool comes first in the MRO, and its __init__ never calls super(), so DebugMixin's never runs. Put the mixin first: class Hammer(DebugMixin, Tool).

HistoryMixin has history = [] in its class body and a record(event) method that appends to self.history. Cart and Wallet are both built on it. After Cart().record("add tea") and Wallet().record("pay"), what does print(Cart().history) print?

  • ['add tea', 'pay']
  • ['add tea']
  • []
  • It stops with AttributeError

Answer: ['add tea', 'pay']. The class body makes one list, and every object of every class built on HistoryMixin appends to it.

Continue this course

Frequently asked questions

What's the difference between __mro__ and mro()?

Only the type. __mro__ is a tuple Python stores when it makes the class, and mro() returns the same classes as a list. For Duck(Walker, Swimmer), type(Duck.__mro__) is tuple, type(Duck.mro()) is list, and Duck.__mro__ == tuple(Duck.mro()) is True.

Can a dataclass use a mixin?

Yes. A @dataclass class Product(ToDictMixin) with the fields name and pence gets its __init__ and __repr__ from @dataclass and to_dict() from the mixin: Product("tea", 120) prints as Product(name='tea', pence=120), and its to_dict() gives {'name': 'tea', 'pence': 120}. Data Classes & Advanced Class Patterns covers inheritance between dataclasses.

Can I call super() in a function outside a class?

Not with no arguments. super() works out the class and the object from the method it's written in, so in a plain function it stops with RuntimeError: super(): __class__ cell not found.

Does the order of the mixins change isinstance()?

No. isinstance() asks whether the class appears anywhere in the object's MRO, so it's True for LoggingMixin whether the class line is (LoggingMixin, BaseModel) or (BaseModel, LoggingMixin). Only which method runs first depends on the order.

Why does mypy say "save" undefined in superclass for my mixin?

Because mypy checks LoggingMixin on its own, and on its own its parent is object, which has no save(). mypy 1.19.1 reports error: "save" undefined in superclass for super().save(), though the program runs. Give the mixin and the model a small shared base class that defines save(), and mypy reports no issues. Advanced Type Hints (Generics, Protocol, TypedDict) shows other ways.

Does Python have interfaces?

Not as a keyword. A mixin often relies on a method it doesn't define, as JSONMixin relies on to_dict() in the exercise below. Type Hints & Static Typing with mypy showed Protocol, which lets a type checker check that a method exists, and Abstract Base Classes (abc) shows how to make Python refuse to create an object whose class leaves a method out.

Related lessons