🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Inheritance: MRO, Mixins, and Composition over Hierarchy

Python OOPđŸŸĸ Free Lesson

Prerequisites

  • !Single inheritance and super()
  • !Classes as objects and attribute lookup order

What You'll Learn

  • 1Read a method resolution order and predict which method runs
  • 2Use cooperative super correctly in multiple inheritance
  • 3Design mixins that do not require their own state
  • 4Decide between inheritance, mixins, and composition
  • 5Spot hierarchy shapes that make change expensive

Inheritance is the most overused tool in object-oriented Python. It is genuinely the right answer when a subtype relationship holds and the parent's contract is stable, and it is the wrong answer in every other case, including most situations where a junior developer reaches for it to reuse a few lines of code. This lesson covers how Python actually resolves methods, how to write mixins that survive reuse, and how to recognise the moment composition is the honest structure.

What inheritance is for

Reuse is the visible benefit, but substitutability is the real contract: anywhere a parent is expected, a child must behave correctly. That requirement, the Liskov substitution principle, is what rules out most bad hierarchies. A class that overrides a method and then raises NotImplementedError for a case the parent supported is not a subtype, and callers written against the parent will break at runtime rather than at compile time.

RelationshipQuestion to askPreferred tool
Is-a, and clients rely on the parent's contractCan I substitute one for the other everywhere?Inheritance
Has-a, and the part has a lifecycle of its ownDoes the component exist independently?Composition
Can-do, and the capability is stateless or self-containedIs the behaviour orthogonal to the main type?Mixin
Shares implementation onlyIs this code identical rather than related?Module-level functions or a helper class
Varies by configurationDo I need instances at runtime?Strategy object

Writing the questions down before opening the class hierarchy saves refactors later. The failure mode to watch for is justifying inheritance with the phrase "it already has the methods I need", because that confuses code sharing with type relationships. Code sharing has cheaper mechanisms.

Reading the method resolution order

Python resolves every attribute lookup by walking a linearised list of classes, printed by the __mro__ attribute, computed by the C3 linearization algorithm. C3 guarantees three things: a class always appears before its bases, local precedence order is preserved, and the order is consistent across all bases. When those constraints cannot be satisfied, Python raises an error at class creation time rather than picking arbitrarily.

python
class Base:
    def describe(self):
        return "Base"


class Left(Base):
    def describe(self):
        return "Left" + super().describe()


class Right(Base):
    def describe(self):
        return "Right" + super().describe()


class Combined(Left, Right):
    pass


print(Combined().describe())          # LeftRightBase
print(Combined.__mro__)
# (Combined, Left, Right, Base, object)

The output is the proof that super() is not "the parent class" but "the next class in the MRO". Inside Left.describe, the call skips to Right, then to Base, so a linear chain of cooperative calls produces the concatenation. This is why the single-inheritance mental model misleads: with multiple inheritance, the same super() call behaves differently depending on the concrete class it was invoked on.

The diamond and cooperative super

The dangerous shape is a diamond, where two branches meet at a shared ancestor. Without cooperative calls, the shared ancestor's method runs twice or not at all; with super() threaded correctly, it runs exactly once.

python
class Validator:
    def __init__(self, **fields):
        self.fields = fields
        self.errors = []

    def validate(self):
        return not self.errors


class Typed(Validator):
    def __init__(self, **fields):
        super().__init__(**fields)
        self.types = {}

    def validate(self):
        for name, expected in self.types.items():
            value = self.fields.get(name)
            if value is not None and not isinstance(value, expected):
                self.errors.append(f"{name}: expected {expected.__name__}")
        return super().validate()


class Required(Validator):
    def __init__(self, **fields):
        super().__init__(**fields)
        self.required = set()

    def validate(self):
        for name in self.required:
            if name not in self.fields:
                self.errors.append(f"{name}: missing")
        return super().validate()


class UserRecord(Required, Typed):
    def __init__(self, **fields):
        super().__init__(**fields)
        self.required = {"name"}
        self.types = {"name": str, "age": int}


record = UserRecord(name="Ada", age="nope")
print(record.validate(), record.errors)   # False ['age: expected int']

The two rules that keep this working are easy to state and easy to break: every __init__ in the chain must call super().__init__, and each class must only add what it owns. Break either one and you get an object missing half its attributes, an error that surfaces only when a particular combination of subclasses is instantiated. If you cannot draw the call chain on a whiteboard, the hierarchy is too complicated for the problem.

Mixins without hidden state

A mixin is a class designed to be combined with others, never instantiated alone, and ideally free of its own instance state. Stateless mixins are trivial to reuse because they depend only on what the host class provides; mixins that introduce fields force every host to initialise them, which is where reuse quietly fails.

python
import json


class ToJsonMixin:
    def to_json(self, indent=2):
        public = {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
        return json.dumps(public, indent=indent, sort_keys=True)

    @classmethod
    def from_json(cls, text):
        return cls(**json.loads(text))


class ToCsvMixin:
    def header(self):
        return [k for k in self.__dict__ if not k.startswith("_")]

    def row(self):
        return [self.__dict__[k] for k in self.header()]


class Product(ToJsonMixin, ToCsvMixin):
    def __init__(self, name, price):
        self.name = name
        self.price = price


p = Product("widget", 9.5)
print(p.to_json())          # { "name": "widget", "price": 9.5 }
print(",".join(p.header()))  # name,price

Both mixins assume the host keeps its public data in instance attributes, which is a documented constraint rather than an accident. Name mixins so the expectation is visible, document what they require, and keep them small enough that a reader can see the whole contract at once. When a mixin starts needing configuration of its own, it is becoming a base class, and you should decide which it is meant to be.

Composition: when the relationship is not a subtype

Composition builds complex objects from simpler ones that own their own state. It shines when the parts are replaceable, have their own lifecycle, or vary independently of the whole. A car that has an engine is the textbook case, and the practical case is any system where you want to swap a component in tests without inheriting its behaviour.

python
class Encoder:
    def encode(self, record):
        raise NotImplementedError


class JsonEncoder(Encoder):
    def encode(self, record):
        return json.dumps(record)


class CsvEncoder(Encoder):
    def encode(self, record):
        keys = list(record)
        values = [str(record[k]) for k in keys]
        return ",".join(keys) + "\n" + ",".join(values)


class Exporter:
    def __init__(self, encoder):
        self._encoder = encoder

    def export(self, records):
        return "\n".join(self._encoder.encode(r) for r in records)


exporter = Exporter(JsonEncoder())
print(exporter.export([{"a": 1}]))   # [{"a": 1}]

Composition also simplifies testing: pass a fake encoder, assert on calls, and move on. The cost is one extra indirection and a constructor argument, which is a small price for the freedom to change one part without touching the other. In practice, most well-designed Python systems are composition with a thin layer of inheritance for genuine subtype contracts.

Signals that a hierarchy needs refactoring

Certain smells recur. A child class that overrides most of the parent's methods is really a sibling, not a subtype. A base class with a growing list of subclasses that share no common behaviour is a namespace pretending to be a hierarchy. Reaching for isinstance checks scattered through business logic means polymorphism is not doing its job. And a change to a mid-level class that forces edits across the tree indicates the abstraction is in the wrong place.

The remedy is usually to push shared implementation down into helper functions, replace conditional branches with small strategy objects, and keep inheritance only where substitution genuinely holds. Refactor when you see the smell rather than when the next feature arrives, because hierarchies are cheap to build and expensive to unwind.

A worked decision, start to finish

Suppose you are adding export formats to a reporting module. Start by asking whether a JSON exporter is a subtype of an exporter in the sense that callers rely on, and the answer is yes only if the interface is a stable contract with a single entry point. If each format also needs configuration, prefer injecting an encoder object as shown above rather than subclassing the exporter for every format, because configuration as constructor arguments is easier to discover than as class variants.

Next consider a capability such as timestamping every record. It has no state of its own beyond what the host already keeps, so a mixin is appropriate, and you should document that the host must expose a modification time. Finally, if the timestamping needs a clock, do not hide the clock inside the mixin; accept it as a field on the host and let the mixin read it. That keeps time sources injectable in tests, which is where hard-coded clocks cause their most expensive failures. Walk through decisions this explicitly for one feature and the pattern transfers to the next ten.

Common Mistakes

Calling the parent class by name instead of super() in a cooperative chain

Fix: Always call super() so the next class in the MRO runs, keeping diamonds correct.

Mixins that assume fields were initialised by a base class that does not exist

Fix: Keep mixins stateless or document exactly which fields the host class must provide.

Justifying inheritance because it reuses a few methods

Fix: Extract shared code into functions or a helper object and reserve inheritance for subtype contracts.

Deep hierarchies with more than three levels

Fix: Flatten with composition or mixins so a change does not ripple through every descendant.

Best Practices

  • Check substitutability before writing a base class
  • Print __mro__ and trace super() when multiple inheritance behaves surprisingly
  • Document the required host fields at the top of every mixin
  • Prefer injecting components in the constructor over inheriting their behaviour
  • Write a test for each subclass combination you actually ship

Key Takeaways

  • super() walks the MRO, which is not the same as the parent class in multiple inheritance
  • C3 linearization keeps ordering predictable and fails loudly when constraints conflict
  • Cooperative super chains require every link to call super().__init__ and to own only its state
  • Mixins are most reusable when they are small, stateless, and documented
  • Composition gives replaceability and simpler tests whenever the relationship is not a subtype
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement