Skip to content

19. Inheritance and polymorphism — Cheat sheet

The essentials of module 19 on one page. Every runnable block on this page is checked against its output.

I want to… Use… Example
reuse a class and add to it a subclass class Ridge(LinearModel): ...
replace a parent method define it again in the child def predict(self, X): ...
extend a parent method super().method(...) return [round(p) for p in super().predict(X)]
run the parent’s __init__ super().__init__(...) super().__init__(fit_intercept=fit_intercept)
see the lookup order Cls.__mro__ or Cls.mro() [c.__name__ for c in Cls.__mro__]
find where a method is defined walk the MRO with vars() next(c for c in Cls.__mro__ if "fit" in vars(c))
test “is some kind of” isinstance(obj, Base) isinstance(model, BaseEstimator)
test one class relation issubclass(Child, Base) issubclass(NotFittedError, ValueError)
list the direct parents Cls.__bases__ StandardScaler.__bases__
add one capability to many classes a mixin, listed first class Scaler(TransformerMixin, BaseEstimator)
read constructor parameters inspect.signature(cls.__init__) .parameters.values()
read or write an attribute by name getattr(), setattr() getattr(est, "n_neighbors")
copy a model without its learned state type(est)(**est.get_params()) clone(knn)
check an interface at run time callable(getattr(obj, name, None)) callable(getattr(m, "predict", None))
force subclasses to implement a method abc.ABC + @abstractmethod class Base(ABC): ...
list the methods still missing Cls.__abstractmethods__ sorted(Half.__abstractmethods__)
test what a container can do collections.abc isinstance(x, Sequence)
type a parameter by its methods typing.Protocol def report(m: SupportsPredict)
use a protocol with isinstance() @runtime_checkable isinstance(obj, SupportsPredict)
register every subclass __init_subclass__ class Csv(Exporter, fmt="csv")
reuse behavior without is-a composition: hold the part self.scaler = scaler
from typing import Self
class Estimator:
def fit(self, X: list[list[float]], y: list[float]) -> Self:
self.n_features_in_ = len(X[0])
return self
def name(self) -> str:
return type(self).__name__ # the real class, also in a subclass
class PriceModel(Estimator): # inherits fit() and name()
def name(self) -> str: # override
return "price:" + super().name() # extend
model = PriceModel().fit([[1200.0]], [250_000.0])
print(model.name(), vars(model), [c.__name__ for c in PriceModel.__mro__])
Output
price:PriceModel {'n_features_in_': 1} ['PriceModel', 'Estimator', 'object']
obj.attr lookup order Notes
1. vars(obj): the object’s own data set in __init__ or later
2. type(obj) methods and class attributes
3. each class of type(obj).__mro__, left to right the first match wins
not found AttributeError: 'X' object has no attribute 'y'
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
class Child(Parent):
def __init__(self, alpha: float = 1.0, fit_intercept: bool = True) -> None:
super().__init__(fit_intercept=fit_intercept) # parent sets its part
self.alpha = alpha # child sets the new part
def predict(self, X):
raw = super().predict(X) # parent's result
return [max(p, 0.0) for p in raw] # post-process
@classmethod
def from_config(cls, config):
return super().from_config(config) # works in class methods too
  • super() = “the next class after this one in the MRO of type(self)”, not “my parent”.
  • Python never calls the parent’s __init__ for you.
  • super() without arguments works only inside a method defined in a class body.
C3 rule Effect
a class comes before its parents Child before Base
parents keep the listed order class C(A, B): A before B
each class appears once; a shared parent comes after all its children the diamond top runs last, once
no order satisfies all rules TypeError: Cannot create a consistent method resolution order (MRO)
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
print([cls.__name__ for cls in D.__mro__])
Output
['D', 'B', 'C', 'A', 'object']
class Root:
def describe(self) -> list[str]:
return ["Root"] # ends the chain: no super()
class Validated(Root):
def describe(self) -> list[str]:
return ["Validated", *super().describe()]
class Logged(Root):
def describe(self) -> list[str]:
return ["Logged", *super().describe()]
class Safe(Validated, Logged):
pass
print(Safe().describe())
Output
['Validated', 'Logged', 'Root']
Rule Why
every method in the chain calls super() exactly once each class runs once
a root class ends the chain object has no describe() or fit()
same signature in every class of the chain each class passes on what the next one needs
__init__(self, *, own=..., **kwargs) + super().__init__(**kwargs) each class takes its keywords; object.__init__() rejects leftovers
never call Parent.method(self) in a cooperative class skips classes or runs one twice
Rule Example
one capability per mixin TransformerMixin adds only fit_transform()
no __init__, no own data (or a cooperative __init__) the host class owns the state
relies on host methods fit_transform() calls self.fit() and self.transform()
name ends in Mixin LoginRequiredMixin, ClassifierMixin
list it left of the base class class View(LoginRequiredMixin, ListView)
scikit-learn mixin Adds Needs from the host
TransformerMixin fit_transform(X, y=None) fit(), transform()
RegressorMixin score(X, y) = R² predict()
ClassifierMixin score(X, y) = accuracy predict()
ClusterMixin fit_predict(X) fit() that sets labels_
import inspect
from typing import Any, Self
class BaseEstimator:
@classmethod
def _get_param_names(cls) -> list[str]:
params = inspect.signature(cls.__init__).parameters.values()
skip = (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
return [p.name for p in params if p.name != "self" and p.kind not in skip]
def get_params(self) -> dict[str, Any]:
return {name: getattr(self, name) for name in self._get_param_names()}
def set_params(self, **params: Any) -> Self:
valid = self._get_param_names()
for name, value in params.items():
if name not in valid:
raise ValueError(f"Invalid parameter {name!r}. Valid: {valid}")
setattr(self, name, value)
return self
class KNNClassifier(BaseEstimator):
def __init__(self, n_neighbors: int = 5) -> None:
self.n_neighbors = n_neighbors # store unchanged, same name
knn = KNNClassifier().set_params(n_neighbors=15)
fresh = type(knn)(**knn.get_params()) # clone: same settings, no learned state
print(knn.get_params(), fresh.get_params(), fresh is knn)
Output
{'n_neighbors': 15} {'n_neighbors': 15} False
Convention Breaks if ignored
__init__ stores each argument unchanged under its own name get_params() raises AttributeError
no *args / **kwargs in __init__ those settings are invisible to get_params()
validation and derived values go in fit(), not in __init__ a check in __init__ (not a property) is skipped by set_params()
learned attributes end with _ check_is_fitted() cannot tell fitted from unfitted
fit() and set_params() return self chained calls fail on None
Style Code Note
just call it model.predict(X) AttributeError at the call
LBYL if callable(getattr(m, "predict", None)): check before long work
EAFP, safe try: f = m.score / except AttributeError: / else: f(X, y) guard only the lookup
EAFP, unsafe try: m.score(X, y) / except AttributeError: hides bugs inside score()

Standard library duck typing: csv.reader() takes any iterable of strings; json.dump() takes any object with write(); sum() takes any iterable; len() takes any object with __len__ (module 20).

from abc import ABC, abstractmethod
class Exporter(ABC):
@property
@abstractmethod
def extension(self) -> str: ... # abstract property: @abstractmethod innermost
@abstractmethod
def export(self, rows: list[dict[str, object]]) -> str: ...
def filename(self, stem: str) -> str: # concrete method built on abstract parts
return f"{stem}.{self.extension}"
class CsvExporter(Exporter):
extension = "csv" # a class attribute satisfies the abstract property
def export(self, rows: list[dict[str, object]]) -> str:
return "\n".join(",".join(str(v) for v in row.values()) for row in rows)
print(sorted(Exporter.__abstractmethods__), CsvExporter().filename("churn"))
print(CsvExporter().export([{"id": "C00001", "churned": 0}]))
Output
['export', 'extension'] churn.csv
C00001,0
collections.abc isinstance() is True for
Iterable list, tuple, str, dict, set, range, files, generators
Sized anything with __len__ (structural check by __subclasshook__)
Sequence list, tuple, str, range (ordered, indexable)
MutableSequence list
Mapping dict and any mapping (read-only interface; MutableMapping adds writes)
Callable functions, classes, objects with __call__

Base.register(OtherClass) makes OtherClass a virtual subclass: isinstance() says True, but no methods are inherited and nothing is checked.

from typing import Protocol, runtime_checkable
@runtime_checkable
class SupportsPredict(Protocol):
def predict(self, X: list[list[float]]) -> list[float]: ...
class Constant: # matches by structure: no base class
def predict(self, X: list[list[float]]) -> list[float]:
return [376_000.0 for _ in X]
class OneRow: # wrong signature, still passes the runtime check
def predict(self, row: list[float]) -> float:
return 376_000.0
print(isinstance(Constant(), SupportsPredict), isinstance(OneRow(), SupportsPredict))
Output
True True
Fact Detail
checked by mypy or pyright, before the code runs
@runtime_checkable + isinstance() checks that the names exist; not signatures, not return types, not even callable()
isinstance() without the decorator TypeError: Instance and class checks can only be used with @runtime_checkable protocols
issubclass() with data members in the protocol TypeError: Protocols with non-method members don't support issubclass()
instantiating a protocol TypeError: Protocols cannot be instantiated
Need Choose
a quick script, standard library style duck typing
a check before long work, at run time callable(getattr(...))
your own family of classes that share code ABC with concrete methods
plugins that must implement a method, with an early error ABC
a function that must accept third-party objects Protocol + mypy
a type check on objects you cannot edit Protocol

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

Situation Choose Why
LinearRegression and BaseEstimator inheritance a regression is an estimator
a model that scales its input first composition it uses a scaler; both define fit()
KNN with a choice of distance composition swap the distance at run time
a loss history that “is a list” composition a list’s sort(), clear() and append() of anything break it
Euclidean and Manhattan versions of a class composition one class per option multiplies classes
score() for every regressor inheritance (a mixin) one method, shared by all regressors
Sign of misused inheritance Symptom
the child turns off a parent method def sort(self): raise NotImplementedError
two parents define the core method only one fit() runs
the class name contains “And” ScalerAndRegressor
five or more levels the fragile base class problem: a parent change breaks distant children
class Plugin:
registry: dict[str, type["Plugin"]] = {}
def __init_subclass__(cls, *, name: str, **kwargs: object) -> None:
super().__init_subclass__(**kwargs)
Plugin.registry[name] = cls # runs once per subclass, at class creation
class MeanImputer(Plugin, name="mean"):
pass
class MedianImputer(Plugin, name="median"):
pass
print({key: cls.__name__ for key, cls in Plugin.registry.items()})
Output
{'mean': 'MeanImputer', 'median': 'MedianImputer'}
class MinilearnError(Exception):
"""Base of every library error: catch them all with one except."""
class NotFittedError(MinilearnError, AttributeError):
"""Also an AttributeError, so older except clauses still catch it."""
try:
raise NotFittedError("call fit() first")
except AttributeError as err:
print(type(err).__name__, [c.__name__ for c in NotFittedError.__mro__[1:4]])
Output
NotFittedError ['MinilearnError', 'AttributeError', 'Exception']
  • A child __init__ replaces the parent’s. Call super().__init__(...), or the parent’s attributes never exist.
  • super() follows the MRO of the object’s class. In a diamond, super() in one parent can reach its sibling.
  • Parent.method(self) in a cooperative class skips classes or runs one twice. Use super() in every class of the chain.
  • The root of a chain must not call super().method(): object has no such method.
  • A mixin listed to the right of the base class cannot override the base’s methods.
  • class C(Base, Child) with Child(Base) is an impossible MRO: TypeError at class creation.
  • With two parents that both define fit() and __init__(), only the first one’s runs. Prefer composition.
  • @abstractmethod does nothing without ABC (or metaclass=ABCMeta) in the class tree.
  • An ABC checks names, not signatures. def predict(self) counts as an implementation.
  • @abstractmethod goes innermost: below @property, @classmethod or @staticmethod.
  • A runtime protocol check passes for predict = 0. Run mypy, and use callable() at run time.
  • type(obj) is Base is False for subclasses. Use isinstance(obj, Base).
  • get_params() needs each __init__ argument stored under its own name. self.k = n_neighbors breaks it.
  • Subclassing list or dict inherits every method, including the ones that break your rules. Hold a list instead.
  • Printing an object without __repr__ shows a memory address that changes per run. Print type(obj).__name__ and its parameters; module 20 adds __repr__.