Skip to content

Inheritance and polymorphism

How classes reuse and specialize each other, and when not to inherit at all. Interfaces (ABCs and Protocols) are on ABC vs Protocol.

I want to… Use… Example
reuse a class and add to it a subclass class AdminUser(User): ...
replace a parent method define it again in the child def render(self): ...
extend a parent method super().method(...) return super().render() + footer
run the parent’s __init__ super().__init__(...) super().__init__(name, age)
pass unknown options up the chain **kwargs + super().__init__(**kwargs) cooperative __init__
see the lookup order Cls.__mro__ or Cls.mro() [c.__name__ for c in Cls.__mro__]
find which class defines a method walk the MRO next(c for c in Cls.__mro__ if "save" in vars(c))
list the direct parents Cls.__bases__ (User,)
list the direct children Cls.__subclasses__() plugin discovery
test “is some kind of” isinstance(obj, Base) isinstance(err, OSError)
test a class relation issubclass(Child, Base) issubclass(bool, int) → True
add one capability to many classes a mixin, listed first class Order(JsonMixin, Model)
reuse behavior without is-a composition: hold the part self.storage = storage
forward many calls to a held object __getattr__ delegation see dunder methods
make a custom dict or list collections.UserDict / UserList, or collections.abc class CaseInsensitiveDict(UserDict)
accept any object with the right methods duck typing def save(fp): fp.write(...)
choose behavior by the argument’s type functools.singledispatch @to_json.register
choose behavior by the object’s class a method override (polymorphism) shape.area()
force subclasses to write a method abc.ABC + @abstractmethod ABC vs Protocol
register every subclass on creation __init_subclass__ class CsvExporter(Exporter, fmt="csv")
mark an override for type checkers @typing.override (3.12+) mypy flags a typo in the name
stop further subclassing (type checkers) @typing.final @final class Token:
build an error family a base exception + subclasses class AppError(Exception)
class Notifier:
def __init__(self, sender: str) -> None:
self.sender = sender
def format(self, text: str) -> str:
return f"[{self.sender}] {text}"
def send(self, text: str) -> str: # a template: calls methods a child may override
return f"{self.channel()}: {self.format(text)}"
def channel(self) -> str: # a hook
return "log"
class EmailNotifier(Notifier):
def __init__(self, sender: str, to: str) -> None:
super().__init__(sender) # the parent sets its part
self.to = to # the child adds its own
def channel(self) -> str: # replace
return f"email to {self.to}"
def format(self, text: str) -> str: # extend
return super().format(text).upper()
n = EmailNotifier("billing", "ada@example.com")
print(n.send("invoice ready"))
print(vars(n), [c.__name__ for c in EmailNotifier.__mro__])
Output
email to ada@example.com: [BILLING] INVOICE READY
{'sender': 'billing', 'to': 'ada@example.com'} ['EmailNotifier', 'Notifier', 'object']
Child choice Code When
inherit write nothing the parent’s behavior fits
replace def m(self): ... without super() the behavior must differ
extend def m(self): r = super().m(); ... add a step before or after
hook the parent calls self._step(); the child overrides _step vary one step of a fixed algorithm
new method a name the parent lacks extra behavior only the child has

self is always the real object. A parent method that calls self.channel() runs the child’s version: this is how overrides plug into parent code.

Fact Detail
meaning “the next class after this one in type(self).__mro__”, not “my parent”
super().__init__(...) Python never calls the parent’s __init__ for you
works in instance methods, class methods, __init_subclass__, properties
zero-argument form only inside a method defined in a class body
super(Cls, self) the old explicit form; same meaning, rarely needed
Parent.method(self) a direct call: skips the MRO; breaks multiple inheritance
from typing import Self
class Child(Parent):
def __init__(self, *, extra: int = 0, **kwargs) -> None:
super().__init__(**kwargs) # the parent takes its options
self.extra = extra # then the child's part
@classmethod
def from_config(cls, config: dict) -> Self:
return super().from_config(config) # cls stays the subclass
@property
def label(self) -> str:
return super().label + "!" # extend a parent property

The MRO is the list of classes Python searches for an attribute, left to right. Python computes it with the C3 linearization when it creates the class.

class Base:
def save(self) -> str:
return "Base"
class Timestamped(Base):
def save(self) -> str:
return "Timestamped>" + super().save()
class Validated(Base):
def save(self) -> str:
return "Validated>" + super().save()
class Order(Timestamped, Validated): # a diamond: both parents share Base
pass
print([c.__name__ for c in Order.__mro__])
print(Order().save()) # super() in Timestamped reaches its sibling, Validated
print(next(c.__name__ for c in Order.__mro__ if "save" in vars(c))) # first match
print([c.__name__ for c in bool.__mro__], [c.__name__ for c in KeyError.__mro__])
Output
['Order', 'Timestamped', 'Validated', 'Base', 'object']
Timestamped>Validated>Base
Timestamped
['bool', 'int', 'object'] ['KeyError', 'LookupError', 'Exception', 'BaseException', 'object']
C3 rule Effect
a class comes before its parents Order before Timestamped
parents keep the order you list class C(A, B): A before B
each class appears once; a shared parent comes after all its children Base runs last, once
no order satisfies all rules TypeError when the class is created
class A:
pass
class B(A):
pass
class C(A, B): # A must come before B (listed order) and after B (B is a child of A)
pass
Output
TypeError: Cannot create a consistent method resolution order (MRO) for bases A, B

Every class in the chain takes its own keyword arguments and passes the rest on with super(). A root class ends the chain.

class Component: # the root: ends the chain
def __init__(self, **kwargs: object) -> None:
super().__init__(**kwargs) # object.__init__() rejects leftovers: a typo fails
def describe(self) -> list[str]:
return [] # no super(): object has no describe()
class Named(Component):
def __init__(self, *, name: str, **kwargs: object) -> None:
super().__init__(**kwargs)
self.name = name
def describe(self) -> list[str]:
return [f"name={self.name}", *super().describe()]
class Cached(Component):
def __init__(self, *, ttl: int = 60, **kwargs: object) -> None:
super().__init__(**kwargs)
self.ttl = ttl
def describe(self) -> list[str]:
return [f"ttl={self.ttl}", *super().describe()]
class Service(Named, Cached):
pass
s = Service(name="users", ttl=30)
print(s.describe(), [c.__name__ for c in Service.__mro__][:4])
try:
Service(name="users", tll=30) # typo in an option
except TypeError as err:
print(err)
Output
['name=users', 'ttl=30'] ['Service', 'Named', 'Cached', 'Component']
object.__init__() takes exactly one argument (the instance to initialize)
Why does the error name object?

No class in the chain takes tll, so it reaches object.__init__(), which accepts no arguments besides the instance. The message does not name the bad keyword, but a misspelled option fails loudly instead of being ignored.

Rule Why
every method in the chain calls super() once each class runs exactly once
a root class ends the chain without super().method() object has no such method
the same signature in every class of the chain any class can be next
__init__(self, *, own=..., **kwargs) + super().__init__(**kwargs) each class takes its keywords
keyword arguments only positional order changes with the MRO
never Parent.method(self) in the chain skips classes or runs one twice

A mixin is a small class that adds one capability. It is never used alone and relies on methods or attributes of its host class.

import json
class ReprMixin:
def __repr__(self) -> str: # works for any class with simple vars()
fields = ", ".join(f"{k}={v!r}" for k, v in vars(self).items())
return f"{type(self).__name__}({fields})"
class JsonMixin:
def to_json(self) -> str: # relies on the host storing JSON-friendly values
return json.dumps(vars(self), sort_keys=True)
class Customer(ReprMixin, JsonMixin): # mixins first, the main base last
def __init__(self, customer_id: str, plan: str) -> None:
self.customer_id = customer_id
self.plan = plan
c = Customer("C00001", "basic")
print(c, c.to_json())
Output
Customer(customer_id='C00001', plan='basic') {"customer_id": "C00001", "plan": "basic"}
Rule Example
one capability per mixin JsonMixin adds only to_json()
no __init__ and no own state (or a cooperative __init__) the host owns the data
name ends in Mixin LoginRequiredMixin, TransformerMixin
list it left of the main base class class View(LoginRequiredMixin, TemplateView)
document what it needs from the host “needs fit() and transform()”
Mixins in the wild Adds
socketserver.ThreadingMixIn one thread per request
collections.abc.Sequence, Mapping (as bases) index, count, get, items and more from a few methods
Django LoginRequiredMixin, PermissionRequiredMixin access checks on class-based views
scikit-learn TransformerMixin, ClassifierMixin fit_transform(), score()
from collections import UserDict
class LowerDict(dict): # dict's C code skips your __setitem__ in some paths
def __setitem__(self, key: str, value: object) -> None:
super().__setitem__(key.lower(), value)
class LowerUserDict(UserDict): # UserDict routes every write through __setitem__
def __setitem__(self, key: str, value: object) -> None:
super().__setitem__(key.lower(), value)
d, u = LowerDict(A=1), LowerUserDict(A=1)
d.update(B=2)
u.update(B=2)
d["C"] = 3
u["C"] = 3
print(sorted(d), sorted(u))
Output
['A', 'B', 'c'] ['a', 'b', 'c']
Want Base class
a dict with custom writes or reads collections.UserDict or collections.abc.MutableMapping
a list with custom writes collections.UserList or collections.abc.MutableSequence
a dict with a default for missing keys dict + __missing__, or collections.defaultdict
a str with extra methods only str (methods that return str return a plain str)
a value type such as Money composition: hold an int or a Decimal

Rule of thumb: inherit for is-a, when the child can replace the parent everywhere (Liskov substitution). Compose for has-a, for swappable parts and to reuse a few methods. When in doubt, compose.

class MemoryStorage:
def __init__(self) -> None:
self._data: dict[str, str] = {}
def get(self, key: str) -> str | None:
return self._data.get(key)
def set(self, key: str, value: str) -> None:
self._data[key] = value
class Cache: # has a storage; does not inherit one
def __init__(self, storage: MemoryStorage, prefix: str = "cache:") -> None:
self.storage = storage # swap in a Redis or file storage with the same methods
self.prefix = prefix
self.hits = 0
def get(self, key: str) -> str | None:
value = self.storage.get(self.prefix + key)
self.hits += value is not None
return value
def set(self, key: str, value: str) -> None:
self.storage.set(self.prefix + key, value)
cache = Cache(MemoryStorage())
cache.set("user:7", "ada")
print(cache.get("user:7"), cache.get("user:8"), cache.hits)
Output
ada None 1
Situation Choose Why
AdminUser and User inheritance an admin is a user everywhere
an exception family (NotFoundError(AppError)) inheritance except AppError catches all
a framework base class (TestCase, nn.Module, Django View) inheritance the framework calls your overrides
a service that uses a database, a cache or an HTTP client composition swap the part in tests and in production
a stack, a queue or a history that “is a list” composition inheriting list exposes sort(), insert(), clear()
one class per option (JsonCsvUploader, XmlS3Uploader) composition combinations multiply classes
a behavior chosen at run time composition (strategy) assign another object or function
one small method shared by many classes a mixin, or a function no state, no is-a
Sign of misused inheritance Symptom
the child turns off a parent method def append(self, x): raise NotImplementedError
two parents define the core method only one save() runs
the class name contains “And” ParserAndUploader
deep trees (four or more levels) the fragile base class problem: a parent change breaks distant children

Polymorphism means one call works on many types: each type gives its own behavior. Python finds the method at run time on the object’s class, so the types need no common base. This is duck typing: “if it has area(), it is a shape”.

import io
import math
class Circle:
def __init__(self, r: float) -> None:
self.r = r
def area(self) -> float:
return math.pi * self.r**2
class Square: # no common base class with Circle
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side**2
def total_area(shapes: list) -> float:
return round(sum(s.area() for s in shapes), 2) # any object with area()
def write_report(fp, lines: list[str]) -> None: # any object with write()
for line in lines:
fp.write(line + "\n")
buf = io.StringIO() # a file-like object in memory: a test double for a real file
write_report(buf, ["a", "b"])
print(total_area([Circle(1), Square(2)]), repr(buf.getvalue()))
print(len("abc"), len([1, 2]), len({"k": 1})) # len() is polymorphic: __len__
Output
7.14 'a\nb\n'
3 2 1
Style Code Note
just call it obj.area() AttributeError at the call if it is missing
LBYL (“look before you leap”) if callable(getattr(obj, "area", None)): check before long work
EAFP (“easier to ask forgiveness”) try: f = obj.area / except AttributeError: / else: f() guard only the lookup
EAFP, too wide try: obj.area() / except AttributeError: hides bugs inside area()
isinstance() on a concrete class if isinstance(obj, Circle): breaks duck typing; use a method or an ABC
type hint def total_area(shapes: list[HasArea]) a Protocol: see ABC vs Protocol

Duck typing in the standard library: json.dump() takes any object with write(); csv.reader() takes any iterable of strings; sum() takes any iterable; with takes any object with __enter__ and __exit__.

When behavior depends on the type of an argument you do not own, use functools.singledispatch instead of an isinstance() chain:

from datetime import date
from decimal import Decimal
from functools import singledispatch
@singledispatch
def to_json(value: object) -> object:
raise TypeError(f"cannot serialize {type(value).__name__}")
@to_json.register
def _(value: date) -> str: # dispatch on the first argument's type
return value.isoformat()
@to_json.register
def _(value: Decimal) -> str:
return str(value)
print(to_json(date(2024, 5, 1)), to_json(Decimal("9.99")))
Output
2024-05-01 9.99
class AppError(Exception):
"""Base of every error of this app: catch them all with one except."""
class NotFoundError(AppError, LookupError): # also a LookupError for old callers
def __init__(self, kind: str, key: object) -> None:
super().__init__(f"{kind} {key!r} not found")
self.kind, self.key = kind, key
try:
raise NotFoundError("user", 7)
except AppError as err:
print(err, "|", err.kind, isinstance(err, LookupError))
Output
user 7 not found | user True
  • Child __init__ replaces the parent’s. Symptom: AttributeError for an attribute the parent sets. Fix: call super().__init__(...).
  • super() is not “my parent”. Symptom: in a diamond, super() reaches a sibling class. Fix: read Cls.__mro__; design every class of the chain to cooperate.
  • Parent.method(self) in a chain. Symptom: a class runs twice or never. Fix: use super() in every class.
  • Root calls super().method(). Symptom: AttributeError: 'super' object has no attribute 'method'. Fix: the root class ends the chain.
  • Positional arguments in cooperative __init__. Symptom: values land in the wrong class when the MRO changes. Fix: keyword-only arguments and **kwargs.
  • Mixin on the right. Symptom: when the base class also defines the method (for example __repr__), the base’s version wins. Fix: list mixins before the main base class.
  • Impossible MRO. Symptom: TypeError: Cannot create a consistent method resolution order. Fix: list a child before its parent, or drop the redundant base.
  • Subclassing dict or list. Symptom: update(), __init__() or extend() skip your override. Fix: subclass UserDict / UserList or a collections.abc class.
  • Subclass breaks the contract. Symptom: code that works with the parent fails or gives wrong results with the child. Fix: keep the parent’s arguments, return types and errors; otherwise compose.
  • type(obj) is Base. Symptom: False for every subclass. Fix: isinstance(obj, Base).
  • isinstance() chains. Symptom: each new type means editing the chain. Fix: a method on each class, or singledispatch.
  • except AttributeError around a whole call. Symptom: real bugs inside the method are hidden. Fix: guard only the attribute lookup.
  • Deep hierarchies. Symptom: a small parent change breaks distant children. Fix: keep trees shallow; prefer composition.