19. Inheritance and polymorphism
Module 18 built a scaler, a linear regression and a dataset as separate classes. They repeat the same ideas: every model has fit(), fit() returns self, and every model stores its settings. This module removes the repetition. You build a small family of classes that share code, in the same way that scikit-learn builds its 200 estimators on a few base classes. Then you learn how one piece of code can work with every member of the family, and how to state the rules that a new member must follow.
What you will learn
Section titled “What you will learn”- Build a subclass, override a method, and extend a parent method with
super(). - Read the method resolution order (
__mro__) and predict which method Python runs, also in a diamond. - Write cooperative classes and mixins, and combine them as scikit-learn does:
class StandardScaler(TransformerMixin, BaseEstimator). - Write a generic
get_params()andset_params()withinspect.signature. - Choose between inheritance and composition with a clear rule of thumb.
- Define what a model must provide with duck typing, an abstract base class (
abc.ABC) or atyping.Protocol, and know the limits of each.
Prerequisites
Section titled “Prerequisites”- 18. Classes and objects:
class,__init__,self, attributes, methods,@classmethodand@property. - 12. Type hints: annotations,
Selfand a first look atProtocoland mypy. - 06. Errors and debugging: the exception hierarchy, base classes and subclasses, EAFP and LBYL.
- 05. Functions:
*args,**kwargsand signatures. - The course datasets in a
data/folder: Get the data. This module usesdata/houses.csvanddata/customers.csv.
Concepts
Section titled “Concepts”Why inheritance
Section titled “Why inheritance”A machine learning library has many models, and they share most of their plumbing. Every model stores its settings, learns in fit(), returns self from fit() and has a way to report its quality. If each class repeats this code, a bug fix must be made in every class.
Inheritance lets a new class reuse the code of an existing class and add to it. The existing class is the parent class (also called the base class or superclass). The new class is the child class (also called the subclass). Module 06 met the same words for exceptions: ValueError is a subclass of Exception.
Write the parent in parentheses after the class name:
from typing import Self
class Estimator: """Behavior that every model shares."""
def fit(self, X: list[list[float]], y: list[float]) -> Self: self.n_features_in_ = len(X[0]) return self
def describe(self) -> str: return f"{type(self).__name__} with {self.n_features_in_} feature(s)"
class PriceModel(Estimator): """A model for house prices. It adds nothing yet."""
model = PriceModel().fit([[1200.0], [1850.0]], [250_000.0, 410_000.0])print(model.describe())print(isinstance(model, PriceModel), isinstance(model, Estimator))print(issubclass(PriceModel, Estimator), issubclass(Estimator, PriceModel))print(PriceModel.__bases__[0].__name__, Estimator.__bases__[0].__name__)PriceModel with 1 feature(s)True TrueTrue FalseEstimator objectPriceModel defines no method, yet it has fit() and describe(): it inherits them. Inside describe(), type(self) is the class of the real object, so the text says PriceModel, not Estimator. isinstance() is True for the class and for every parent. issubclass() works one way only: a price model is an estimator, but an estimator is not always a price model. Every class without a written parent inherits from object, the root of all Python classes.
This “is a” test is the heart of inheritance. A PriceModel is an Estimator, so any code written for estimators accepts it. This relation is called the is-a relationship.
Attribute lookup and overriding
Section titled “Attribute lookup and overriding”When you write model.describe(), Python searches for the name describe in a fixed order:
- the object’s own attributes (the dict that
vars(model)shows); - the object’s class;
- the parent classes, in order, up to
object.
The first match wins. So a child class can override a parent method: it defines a method with the same name, and Python finds the child’s version first.
class LogPriceModel(Estimator): def describe(self) -> str: # overrides Estimator.describe return "log-price model"
logged = LogPriceModel().fit([[1200.0]], [250_000.0])print(logged.describe())print(vars(logged))print("describe" in vars(LogPriceModel), "fit" in vars(LogPriceModel))log-price model{'n_features_in_': 1}True Falsevars(logged) holds only the data of this object. The methods live in the classes: describe sits in LogPriceModel itself, and fit is found one level up, in Estimator. A child has three choices for each parent method:
| Choice | How | Use it when |
|---|---|---|
| Inherit | do not define the method | the parent’s behavior is right |
| Replace | define the method, do not call the parent | the child needs a different behavior |
| Extend | define the method and call the parent’s version with super() |
the child adds a step before or after the parent’s work |
super(): extend a parent method
Section titled “super(): extend a parent method”super() returns a helper object that finds methods in the parent classes. super().describe() runs the parent’s describe() on the same object. The most common use is in __init__: the child sets its own attributes and lets the parent set the rest.
class RoundedModel(Estimator): def __init__(self, step: float) -> None: self.step = step
def describe(self) -> str: base = super().describe() # run Estimator.describe first return f"{base}, rounds to {self.step:,.0f}"
rounded = RoundedModel(step=1000).fit([[1200.0]], [250_000.0])print(rounded.describe())RoundedModel with 1 feature(s), rounds to 1,000Python does not call the parent’s __init__ for you. If a child defines __init__ and forgets super().__init__(), the parent’s attributes never exist:
class Scaler: def __init__(self, with_mean: bool = True) -> None: self.with_mean = with_mean
class RobustScaler(Scaler): def __init__(self, quantile_range: tuple[float, float] = (25.0, 75.0)) -> None: self.quantile_range = quantile_range # forgot super().__init__()
scaler = RobustScaler()print(scaler.quantile_range)print(scaler.with_mean)(25.0, 75.0)AttributeError: 'RobustScaler' object has no attribute 'with_mean'The fix passes the parent’s argument on:
class RobustScaler(Scaler): def __init__( self, with_mean: bool = True, quantile_range: tuple[float, float] = (25.0, 75.0), ) -> None: super().__init__(with_mean=with_mean) self.quantile_range = quantile_range
scaler = RobustScaler(with_mean=False)print(scaler.with_mean, scaler.quantile_range)False (25.0, 75.0)The method resolution order (MRO)
Section titled “The method resolution order (MRO)”The search order of step 3 above has a name: the method resolution order (MRO). Every class stores it in the attribute __mro__, a tuple of classes. Python walks this tuple from left to right and stops at the first class that defines the name.
print([cls.__name__ for cls in RoundedModel.__mro__])['RoundedModel', 'Estimator', 'object']With one parent per class, the MRO is simply the chain from the child up to object. A class can also have several parents (next section). Then Python computes the MRO with an algorithm called C3 linearization. You do not need its details. It follows three rules:
- A class comes before its parents.
- The parents keep the order in which the
classstatement lists them. - Each class appears once. A shared parent comes after all of its children.
When no order can follow all three rules, Python refuses to create the class:
class Transformer(Estimator): pass
class BrokenScaler(Estimator, Transformer): # a parent listed before its own child passTypeError: Cannot create a consistent method resolution order (MRO) for bases Estimator, TransformerRule 2 says Estimator comes before Transformer. Rule 1 says Transformer comes before its parent Estimator. Both cannot be true. The fix is to list the more specific class first, or to drop Estimator, which Transformer already brings.
Multiple inheritance and the diamond
Section titled “Multiple inheritance and the diamond”Multiple inheritance means that a class has more than one parent: class SafeStep(Validated, Logged). When two parents share a grandparent, the class tree forms a diamond:
flowchart BT
V["Validated"] --> S["Step"]
L["Logged"] --> S
SS["SafeStep"] --> V
SS --> L
The diamond problem asks two questions. When both parents define a method, which one runs? And does the shared grandparent run twice? Python answers both with the MRO and super():
class Step: def describe(self) -> list[str]: return ["Step"]
class Validated(Step): def describe(self) -> list[str]: return ["Validated", *super().describe()]
class Logged(Step): def describe(self) -> list[str]: return ["Logged", *super().describe()]
class SafeStep(Validated, Logged): pass
print([cls.__name__ for cls in SafeStep.__mro__])print(SafeStep().describe())print(Validated().describe())['SafeStep', 'Validated', 'Logged', 'Step', 'object']['Validated', 'Logged', 'Step']['Validated', 'Step']Look at the second line. Inside Validated.describe(), super() reached Logged, a class that Validated does not know about. In the third line, the same code reaches Step. The reason: super() does not mean “my parent”. It means “the next class in the MRO of the object’s class”. For a SafeStep object, the next class after Validated is Logged. Each class runs once, and Step runs last.
Classes that are written to work this way practice cooperative multiple inheritance. They follow three rules:
- Every method in the chain calls
super()exactly once. - A root class ends the chain: it defines the method and does not call
super()(here,Step). - Every method in the chain accepts the same arguments. For
__init__, each class takes its own keyword arguments and passes the rest on with**kwargs.
class Verbose: def __init__(self, *, verbose: bool = False, **kwargs: object) -> None: super().__init__(**kwargs) self.verbose = verbose
class Checked: def __init__(self, *, check_input: bool = True, **kwargs: object) -> None: super().__init__(**kwargs) self.check_input = check_input
class Trainer(Verbose, Checked): def __init__(self, *, epochs: int = 10, **kwargs: object) -> None: super().__init__(**kwargs) self.epochs = epochs
trainer = Trainer(epochs=5, verbose=True, check_input=False)print([cls.__name__ for cls in Trainer.__mro__])print(vars(trainer))['Trainer', 'Verbose', 'Checked', 'object']{'check_input': False, 'verbose': True, 'epochs': 5}Trainer keeps epochs and passes verbose and check_input on. Verbose keeps verbose and passes check_input on. Checked keeps the last one, and object.__init__() receives nothing. Each __init__ calls super() before it sets its attribute, so the attributes appear in reverse MRO order. Web frameworks and GUI toolkits use this pattern. scikit-learn does not allow **kwargs in an estimator’s __init__, for a reason that Example 2 shows.
Mixins
Section titled “Mixins”A mixin is a small class that adds one capability to other classes. It is not meant to be used alone. It usually has no __init__ and no data of its own. It relies on attributes or methods that the class it is mixed into provides. By convention its name ends in Mixin.
class ToDictMixin: """Add to_dict(): the public attributes of the object as a dict."""
def to_dict(self) -> dict[str, object]: return {k: v for k, v in vars(self).items() if not k.startswith("_")}
class SensorReading(ToDictMixin): def __init__(self, sensor_id: str, celsius: float) -> None: self.sensor_id = sensor_id self.celsius = celsius self._raw = f"{sensor_id},{celsius}"
class Customer(ToDictMixin): def __init__(self, customer_id: str, churned: bool) -> None: self.customer_id = customer_id self.churned = churned
print(SensorReading("S1", 21.7).to_dict())print(Customer("C03991", True).to_dict()){'sensor_id': 'S1', 'celsius': 21.7}{'customer_id': 'C03991', 'churned': True}A sensor reading and a customer are not related. Both get to_dict() from the same ten lines, ready for json.dumps(). scikit-learn uses mixins for the same reason: TransformerMixin gives every transformer fit_transform(), and RegressorMixin gives every regressor score() (Example 3).
Put mixins to the left of the main base class: class StandardScaler(TransformerMixin, BaseEstimator). By rule 2 of the MRO, a class listed first is searched first. So a mixin on the left can override or extend a method of the base class, and a mixin on the right cannot. Web frameworks follow the same rule. In Django, a class-based view adds a login check with a mixin:
from django.contrib.auth.mixins import LoginRequiredMixinfrom django.views.generic import ListView
from .models import Product
class ProductListView(LoginRequiredMixin, ListView): model = Product paginate_by = 50LoginRequiredMixin comes first, so its dispatch() method runs before the one of ListView. It redirects a visitor who is not logged in. With the order reversed, ListView.dispatch() is found first and the check never runs.
Polymorphism and duck typing
Section titled “Polymorphism and duck typing”Polymorphism (Greek for “many forms”) means that one piece of code works with objects of different types, because each type provides the same method in its own way. The loop for model in models: model.fit(X, y) is polymorphic: every model learns in its own way, and the loop does not care which one it has.
Python takes this idea further with duck typing: it never checks the type of an object before a call. It only looks for the method when the call happens. “If it walks like a duck and quacks like a duck, it is a duck.” The standard library is full of it. csv.reader() accepts any iterable of strings: a list, an open file, a StringIO object or a generator.
import csvimport io
lines = ["sensor_id,celsius", "S1,21.7", "S2,22.1"]text = io.StringIO("sensor_id,celsius\nS1,21.7\nS2,22.1\n")from_list = list(csv.reader(lines))from_text = list(csv.reader(text))print(from_list == from_text, from_list[1])True ['S1', '21.7']Duck typing makes code flexible: a class from another library, written years before yours, works if it has the right methods. The price is late errors. A missing method raises AttributeError only when the call runs, maybe after a long training step. Two styles guard against this (module 06): EAFP tries the call and catches the error, and LBYL checks first with hasattr() or callable(getattr(obj, "predict", None)).
Abstract base classes
Section titled “Abstract base classes”Sometimes duck typing is too loose. A team library wants every model to provide fit() and predict(), and it wants a clear error at once when a class forgets one. An abstract base class (ABC) states this contract. It is a class that cannot be instantiated. It marks the methods that every subclass must implement with the decorator @abstractmethod. Such a method is an abstract method. A subclass that implements all abstract methods is a concrete class.
from abc import ABC, abstractmethod
class Regressor(ABC): @abstractmethod def fit(self, X: list[list[float]], y: list[float]) -> Self: ...
@abstractmethod def predict(self, X: list[list[float]]) -> list[float]: ...
Regressor()TypeError: Can't instantiate abstract class Regressor without an implementation for abstract methods 'fit', 'predict'The ... (the Ellipsis object) is a common body for a method that only declares a name. An ABC can also hold normal, concrete methods that build on the abstract ones. Example 6 adds one.
The module collections.abc defines ABCs for the built-in containers. Use them to test what an object can do, not what class it is:
from collections.abc import Iterable, Mapping, Sequence
for value in ([21.7, 22.1], ("S1", "S2"), "S1", {"S1": 21.7}, range(3), {21.7}): print( f"{type(value).__name__:<5} Sequence={isinstance(value, Sequence)!s:<5} " f"Mapping={isinstance(value, Mapping)!s:<5} " f"Iterable={isinstance(value, Iterable)}" )list Sequence=True Mapping=False Iterable=Truetuple Sequence=True Mapping=False Iterable=Truestr Sequence=True Mapping=False Iterable=Truedict Sequence=False Mapping=True Iterable=Truerange Sequence=True Mapping=False Iterable=Trueset Sequence=False Mapping=False Iterable=Truelist, tuple, str and range do not inherit from Sequence in their code. They are registered as virtual subclasses: Sequence.register(range) tells the ABC “treat range as one of yours”. isinstance() then answers True. A set is iterable, but it has no order, so it is not a sequence.
Some one-method ABCs of collections.abc go further. Iterable, Sized, Hashable and Callable define a special class method, __subclasshook__, that checks the structure of a class. A class with an __iter__ method counts as Iterable without inheriting or registering:
class SensorFeed: # no base class, no register() def __iter__(self): return iter([21.7, 22.1])
print(isinstance(SensorFeed(), Iterable), isinstance(SensorFeed(), Sequence))True FalseSequence has no such hook, so it still needs inheritance or register(). An ABC that you write yourself has no hook either, unless you add one.
Protocols: structural typing
Section titled “Protocols: structural typing”An ABC that you write works by name by default: a class satisfies it only if it inherits from it (or is registered). This is nominal typing. Module 12 introduced the other approach, structural typing: a class satisfies an interface if it has the right methods, whatever its parents are. typing.Protocol describes such an interface. It is duck typing that a type checker such as mypy can check before the code runs.
from typing import Protocol, runtime_checkable
@runtime_checkableclass Predictor(Protocol): def predict(self, X: list[list[float]]) -> list[float]: ...
class ConstantModel: # no base class at all def predict(self, X: list[list[float]]) -> list[float]: return [376_000.0 for _ in X]
class BrokenModel: predict = "not a method"
print(isinstance(ConstantModel(), Predictor))print(isinstance(BrokenModel(), Predictor))print(isinstance(3.14, Predictor))TrueTrueFalseConstantModel never mentions Predictor, yet it matches. The decorator @runtime_checkable makes isinstance() work with a protocol. Its check is shallow, and the second line shows the danger:
@runtime_checkable checks |
It does not check |
|---|---|
| that each protocol member exists on the object | that the member is callable |
| the parameters of a method | |
| the return type |
Two more limits: issubclass() fails with a TypeError for a protocol that has data members, and isinstance() fails with a TypeError for a protocol without @runtime_checkable. Use a protocol mainly for the type checker (Example 7), and use isinstance() with it only as a quick sanity check.
ABC, Protocol or duck typing?
Section titled “ABC, Protocol or duck typing?”| Duck typing | ABC (abc.ABC) |
Protocol (typing.Protocol) |
|
|---|---|---|---|
| The class must inherit from it | no | yes (or register(), or a __subclasshook__) |
no |
| Missing method found | at the call | when you create the object | by mypy, before running |
| Can share code with subclasses | no | yes: concrete methods | possible, but rare |
| Works with classes you cannot edit | yes | only with register() |
yes |
| Typical use | small scripts, standard library functions | your own class family, plugin base classes | function parameters, third-party objects |
Composition vs inheritance
Section titled “Composition vs inheritance”Inheritance is not the only way to reuse code. With composition (a module 18 exercise used it), an object holds other objects as attributes and calls them to do part of its work. This is the has-a relationship: a pipeline has a scaler and has a model. Passing a call on to a held object is delegation (module 10 used the word for yield from).
class Report: def __init__(self, formatter: object) -> None: self.formatter = formatter # has-a formatter
def render(self, mae: float) -> str: return f"MAE: {self.formatter.format(mae)}" # delegate
class Thousands: def format(self, value: float) -> str: return f"{value / 1000:,.1f}k"
class Exact: def format(self, value: float) -> str: return f"{value:,.2f}"
for formatter in (Thousands(), Exact()): print(Report(formatter).render(98_765.4321))MAE: 98.8kMAE: 98,765.43The report does not inherit from a formatter. It holds one, so you can swap it at run time.
The phrase “can replace the parent everywhere” is the Liskov substitution principle. Module 22 studies it with the other SOLID principles.
| Question | Inheritance | Composition |
|---|---|---|
| Relation | is-a: a LinearRegression is an estimator |
has-a: a pipeline has a scaler |
| Coupling | tight: the child sees every detail of the parent | loose: only the public methods of the part |
| Change at run time | no: the class is fixed | yes: pass another part |
| Several behaviors | needs multiple inheritance | holds several parts |
| Typical sign of misuse | the child turns off a parent method, or the class name contains “And” | rare; the cost is a few delegating methods |
A deep hierarchy has its own risk, the fragile base class problem: a small change in a parent class breaks children that the author of the parent never saw. Keep hierarchies shallow: two or three levels, plus mixins.
Worked examples
Section titled “Worked examples”Example 1 — Build a family of baseline price models
Section titled “Example 1 — Build a family of baseline price models”Goal: Every real model must beat a baseline: a trivial model that predicts the same price for every house. Build three baselines for data/houses.csv that share their code through inheritance, and compare them.
Step 1 — Load the sizes and prices
Section titled “Step 1 — Load the sizes and prices”import csv
type Rows = list[list[float]]
def load_xy(path: str, features: list[str], target: str) -> tuple[Rows, list[float]]: """Read feature rows X and the target column y from a CSV file.""" with open(path, encoding="utf-8", newline="") as f: records = list(csv.DictReader(f)) X = [[float(rec[name]) for name in features] for rec in records] y = [float(rec[target]) for rec in records] return X, y
X, y = load_xy("data/houses.csv", ["sqft"], "price")X_train, y_train = X[:2400], y[:2400]X_test, y_test = X[2400:], y[2400:]print(len(X_train), len(X_test), X_train[0], y_train[0])2400 600 [2420.0] 1097500.0The type statement (Python 3.12) gives the long type list[list[float]] the short name Rows. X is a list of rows with one feature each, as scikit-learn expects. The file is sorted by sale date, so the first 2,400 sales train the models and the last 600 test them.
Step 2 — Write the base class
Section titled “Step 2 — Write the base class”from statistics import mean, median
class BaselineRegressor: """Predict one constant price for every house: the training mean."""
def fit(self, X: Rows, y: list[float]) -> Self: self.constant_ = self._center(y) return self
def predict(self, X: Rows) -> list[float]: return [self.constant_ for _ in X]
def _center(self, y: list[float]) -> float: return mean(y)
def mae(y_true: list[float], y_pred: list[float]) -> float: """Mean absolute error: the average size of a miss.""" return sum(abs(t - p) for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
base = BaselineRegressor().fit(X_train, y_train)print(f"constant {base.constant_:,.0f} MAE {mae(y_test, base.predict(X_test)):,.0f}")constant 468,342 MAE 225,400The mean absolute error (MAE) is the average distance between the true and the predicted price. fit() does not compute the constant itself. It calls self._center(y). A method like _center is a hook: a step that the base class calls and a subclass can override. The leading underscore says that it is internal (module 18).
Step 3 — Override the hook in a subclass
Section titled “Step 3 — Override the hook in a subclass”class MedianRegressor(BaselineRegressor): """Predict the training median: robust to a few very expensive houses."""
def _center(self, y: list[float]) -> float: return median(y)
med = MedianRegressor().fit(X_train, y_train)print(f"constant {med.constant_:,.0f} MAE {mae(y_test, med.predict(X_test)):,.0f}")constant 369,500 MAE 219,511MedianRegressor has four lines of code. fit() and predict() are inherited. When the inherited fit() calls self._center(y), the search starts at type(self), which is MedianRegressor, so the median version runs. The median gives a lower MAE: a few houses above 2 million pull the mean up, and the median minimizes the absolute error.
Step 4 — Extend a method with super()
Section titled “Step 4 — Extend a method with super()”class RoundedMedianRegressor(MedianRegressor): """The median price, rounded the way an agent quotes it."""
def __init__(self, step: int = 10_000) -> None: self.step = step
def predict(self, X: Rows) -> list[float]: raw = super().predict(X) # found in BaselineRegressor return [round(p / self.step) * self.step for p in raw]
quote = RoundedMedianRegressor(step=25_000).fit(X_train, y_train)print(quote.predict(X_test[:3]))print([cls.__name__ for cls in RoundedMedianRegressor.__mro__])[375000, 375000, 375000]['RoundedMedianRegressor', 'MedianRegressor', 'BaselineRegressor', 'object']MedianRegressor has no predict(), so super().predict(X) walks on and finds the one in BaselineRegressor. The child adds one step after the parent’s work. The MRO shows the full search path. fit() uses _center() from MedianRegressor and predict() from both levels.
Common mistakes:
- Copying
fit()into every subclass to change one line. Move the line that varies into a hook and override only the hook. - Overriding
fit()and forgettingreturn self. Chained calls such asModel().fit(X, y).predict(X)then fail withAttributeError: 'NoneType' object has no attribute 'predict'. - Calling
super().predict()without passingX.super()gives you the parent’s method, but you still pass every argument exceptself.
Example 2 — Give every estimator get_params and set_params
Section titled “Example 2 — Give every estimator get_params and set_params”Goal: A tuning tool, such as grid search in module 37, must read and change the settings of any model without knowing its class. scikit-learn solves this with one base class, BaseEstimator. Rebuild its two key methods with inspect.signature.
Step 1 — Read the parameters of a constructor
Section titled “Step 1 — Read the parameters of a constructor”import inspect
class KNNClassifier: def __init__(self, n_neighbors: int = 5, weights: str = "uniform") -> None: self.n_neighbors = n_neighbors self.weights = weights
sig = inspect.signature(KNNClassifier.__init__)print(sig)for param in sig.parameters.values(): print(f"{param.name:<12} {param.kind.name:<22} default={param.default!r}")(self, n_neighbors: int = 5, weights: str = 'uniform') -> Noneself POSITIONAL_OR_KEYWORD default=<class 'inspect._empty'>n_neighbors POSITIONAL_OR_KEYWORD default=5weights POSITIONAL_OR_KEYWORD default='uniform'The module inspect lets a program look at its own code. inspect.signature() returns the signature of a function (module 05): its parameters with their kinds and defaults. self has no default. inspect marks a missing default with the class inspect.Parameter.empty, which prints as <class 'inspect._empty'>. These settings are the model’s hyperparameters (module 18): values that you choose, not values that the model learns.
Step 2 — Write BaseEstimator
Section titled “Step 2 — Write BaseEstimator”from typing import Any
class BaseEstimator: """get_params() and set_params() for any class that stores its __init__ args."""
@classmethod def _get_param_names(cls) -> list[str]: params = inspect.signature(cls.__init__).parameters.values() return [ p.name for p in params if p.name != "self" and p.kind not in (p.VAR_POSITIONAL, p.VAR_KEYWORD) ]
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} for {type(self).__name__}. " f"Valid: {valid}" ) setattr(self, name, value) return self_get_param_names() is a class method because the names depend only on the class. The key is cls.__init__: when a subclass calls it, cls is the subclass, so Python reads the subclass’s own __init__. getattr(self, name) reads an attribute whose name is a string, and setattr() writes one. This design depends on one convention from module 18: __init__ stores each argument unchanged, under the same name. It also explains why scikit-learn forbids *args and **kwargs in __init__: their names are not in the signature, so get_params() cannot see them.
Step 3 — Inherit the methods
Section titled “Step 3 — Inherit the methods”class KNNClassifier(BaseEstimator): def __init__(self, n_neighbors: int = 5, weights: str = "uniform") -> None: self.n_neighbors = n_neighbors self.weights = weights
class StandardScaler(BaseEstimator): def __init__(self, with_mean: bool = True, with_std: bool = True) -> None: self.with_mean = with_mean self.with_std = with_std
class MeanRegressor(BaselineRegressor, BaseEstimator): """The mean baseline of Example 1, now with get_params()."""
estimators = [ KNNClassifier(n_neighbors=3), StandardScaler(with_std=False), MeanRegressor(),]for est in estimators: print(f"{type(est).__name__:<14} {est.get_params()}")KNNClassifier {'n_neighbors': 3, 'weights': 'uniform'}StandardScaler {'with_mean': True, 'with_std': False}MeanRegressor {}Three classes, one implementation. MeanRegressor defines no __init__, so cls.__init__ is object.__init__, whose signature is (self, /, *args, **kwargs). The filter drops all three parameters, and the model has no hyperparameters. MeanRegressor also shows multiple inheritance at work: it gets fit() and predict() from one parent and get_params() from the other.
Step 4 — Change parameters by name
Section titled “Step 4 — Change parameters by name”knn = KNNClassifier()knn.set_params(n_neighbors=15).set_params(weights="distance")print(knn.get_params()){'n_neighbors': 15, 'weights': 'distance'}set_params() returns self, so calls chain. A grid search runs exactly this: it sets a combination of values, fits, scores, and repeats. A typo must fail loudly, not create a new, unused attribute:
knn.set_params(n_neighbor=7)ValueError: Invalid parameter 'n_neighbor' for KNNClassifier. Valid: ['n_neighbors', 'weights']Step 5 — Clone a model from its parameters
Section titled “Step 5 — Clone a model from its parameters”def clone(estimator: BaseEstimator) -> BaseEstimator: """Return a new, unfitted estimator with the same hyperparameters.""" return type(estimator)(**estimator.get_params())
fitted = MeanRegressor().fit(X_train, y_train)fresh = clone(fitted)print(type(fresh).__name__, fresh.get_params())print(hasattr(fitted, "constant_"), hasattr(fresh, "constant_"))print(clone(KNNClassifier(n_neighbors=7)).get_params())MeanRegressor {}True False{'n_neighbors': 7, 'weights': 'uniform'}type(estimator) is the real class of the object, so clone() works for every subclass without an if. This is polymorphism through the class itself. The clone gets the hyperparameters but no learned attributes. Cross-validation (module 37) uses scikit-learn’s clone() to fit a fresh copy of a model on each fold.
Common mistakes:
- Storing a changed value in
__init__, such asself.k = n_neighbors.get_params()then fails withAttributeError: 'KNNClassifier' object has no attribute 'n_neighbors'. Store each argument under its own name, and put validation infit(). - Accepting
*argsin an estimator’s__init__.get_params()silently drops those values, and scikit-learn’s ownBaseEstimatorrefuses such a class with aRuntimeErrorwhen it reads the parameters. List every hyperparameter by name. - Forgetting that
set_params()must returnself. Chained calls then fail onNone.
Example 3 — Add fit_transform and score with mixins
Section titled “Example 3 — Add fit_transform and score with mixins”Goal: Every scikit-learn transformer has fit_transform(), and every regressor and classifier has score(). Write each method once, in a mixin, then build a scaler and a regression from a mixin plus BaseEstimator, and read their MRO.
Step 1 — Write the metrics and the three mixins
Section titled “Step 1 — Write the metrics and the three mixins”def r2_score(y_true: list[float], y_pred: list[float]) -> float: mean_true = sum(y_true) / len(y_true) ss_res = sum((t - p) ** 2 for t, p in zip(y_true, y_pred, strict=True)) ss_tot = sum((t - mean_true) ** 2 for t in y_true) return 1 - ss_res / ss_tot
def accuracy_score(y_true: list[float], y_pred: list[float]) -> float: return sum(t == p for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
class TransformerMixin: """fit_transform() for any class with fit() and transform()."""
def fit_transform(self, X: Rows, y: list[float] | None = None) -> Rows: return self.fit(X, y).transform(X)
class RegressorMixin: """score() = R² for any class with predict()."""
def score(self, X: Rows, y: list[float]) -> float: return r2_score(y, self.predict(X))
class ClassifierMixin: """score() = accuracy for any class with predict()."""
def score(self, X: Rows, y: list[float]) -> float: return accuracy_score(y, self.predict(X))Module 18 wrote r2_score(): the share of the variance in y that the model explains (1.0 is perfect; 0.0 is no better than predicting the mean). Accuracy is the share of correct predictions. Each mixin calls methods it does not define: fit(), transform() or predict(). The class it is mixed into must provide them.
Step 2 — Build StandardScaler from a mixin and the base
Section titled “Step 2 — Build StandardScaler from a mixin and the base”import math
class StandardScaler(TransformerMixin, BaseEstimator): """Center each column on 0 and scale it to a standard deviation of 1."""
def __init__(self, with_mean: bool = True, with_std: bool = True) -> None: self.with_mean = with_mean self.with_std = with_std
def fit(self, X: Rows, y: list[float] | None = None) -> Self: columns = list(zip(*X, strict=True)) means = [sum(col) / len(col) for col in columns] stds = [ math.sqrt(sum((v - m) ** 2 for v in col) / len(col)) for col, m in zip(columns, means, strict=True) ] n_cols = len(columns) self.mean_ = means if self.with_mean else [0.0] * n_cols self.scale_ = [s or 1.0 for s in stds] if self.with_std else [1.0] * n_cols return self
def transform(self, X: Rows) -> Rows: return [ [(v - m) / s for v, m, s in zip(row, self.mean_, self.scale_, strict=True)] for row in X ]
features = ["tenure_months", "logins_last_30d"]X_cust, y_cust = load_xy("data/customers.csv", features, "churned")scaler = StandardScaler()X_scaled = scaler.fit_transform(X_cust)print([round(m, 2) for m in scaler.mean_], [round(s, 2) for s in scaler.scale_])print(X_cust[0], [round(v, 2) for v in X_scaled[0]])[23.08, 11.74] [19.75, 7.86][72.0, 17.0] [2.48, 0.67]The scaler defines fit() and transform(), and gets fit_transform() from the mixin and get_params() from the base. The first customer has 72 months of tenure, about 2.5 standard deviations above the mean. s or 1.0 replaces a standard deviation of 0 (a constant column) with 1, to avoid a division by zero.
Step 3 — Read the MRO
Section titled “Step 3 — Read the MRO”print([cls.__name__ for cls in StandardScaler.__mro__])for name in ("__init__", "fit", "fit_transform", "get_params"): owner = next(cls for cls in StandardScaler.__mro__ if name in vars(cls)) print(f"{name:<14} found in {owner.__name__}")['StandardScaler', 'TransformerMixin', 'BaseEstimator', 'object']__init__ found in StandardScalerfit found in StandardScalerfit_transform found in TransformerMixinget_params found in BaseEstimatorThe loop repeats Python’s own search: it walks the MRO and stops at the first class whose vars() contains the name.
flowchart BT
SS["StandardScaler<br/>__init__, fit, transform"] --> TM["TransformerMixin<br/>fit_transform"]
SS --> BE["BaseEstimator<br/>get_params, set_params"]
TM --> O["object"]
BE --> O
Step 4 — Score a regression with RegressorMixin
Section titled “Step 4 — Score a regression with RegressorMixin”class LinearRegression(RegressorMixin, BaseEstimator): """Least-squares line for one feature: y = intercept_ + coef_ * x."""
def __init__(self, fit_intercept: bool = True) -> None: self.fit_intercept = fit_intercept
def fit(self, X: Rows, y: list[float]) -> Self: x = [row[0] for row in X] mean_x = sum(x) / len(x) if self.fit_intercept else 0.0 mean_y = sum(y) / len(y) if self.fit_intercept else 0.0 sxy = sum((a - mean_x) * (b - mean_y) for a, b in zip(x, y, strict=True)) sxx = sum((a - mean_x) ** 2 for a in x) self.coef_ = sxy / sxx self.intercept_ = mean_y - self.coef_ * mean_x return self
def predict(self, X: Rows) -> list[float]: return [self.intercept_ + self.coef_ * row[0] for row in X]
lr = LinearRegression().fit(X_train, y_train)sign = "-" if lr.intercept_ < 0 else "+"print(f"price = {lr.coef_:.2f} * sqft {sign} {abs(lr.intercept_):,.0f}")print(f"R² on the test houses: {lr.score(X_test, y_test):.3f}")print(lr.get_params(), [cls.__name__ for cls in LinearRegression.__mro__])price = 316.29 * sqft - 119,064R² on the test houses: 0.561{'fit_intercept': True} ['LinearRegression', 'RegressorMixin', 'BaseEstimator', 'object']score() comes from RegressorMixin and calls the regression’s own predict(). Swap RegressorMixin for ClassifierMixin and the same model would report accuracy instead. Each mixin is one decision, written once.
Common mistakes:
- Listing the mixin after the base class. Here it still works, because
BaseEstimatorhas nofit_transform(). But if the base ever defines that name, the mixin’s version is silently skipped. Mixins go left. - Using a mixin on a class that lacks a required method.
TransformerMixinon a class withouttransform()fails withAttributeErrorat the firstfit_transform()call. - Giving a mixin an
__init__that does not callsuper().__init__(). It cuts the__init__chain of every class after it in the MRO.
Example 4 — Chain training checks with cooperative super()
Section titled “Example 4 — Chain training checks with cooperative super()”Goal: A training step must check its inputs and log its progress. Write each concern as its own class, combine them in a diamond, and see why super() must be used in every class of the chain.
Step 1 — Write one class per concern
Section titled “Step 1 — Write one class per concern”class Model: def fit(self, X: Rows, y: list[float]) -> Self: print(" Model.fit: learning from", len(X), "rows") self.is_fitted_ = True return self
class ValidateInput(Model): def fit(self, X: Rows, y: list[float]) -> Self: print(" ValidateInput.fit: checking lengths") if len(X) != len(y): raise ValueError(f"X has {len(X)} rows but y has {len(y)}") return super().fit(X, y)
class LogTraining(Model): def fit(self, X: Rows, y: list[float]) -> Self: print(" LogTraining.fit: start") result = super().fit(X, y) print(" LogTraining.fit: done") return result
class AuditedModel(ValidateInput, LogTraining): """Validate, then log, then learn."""
print([cls.__name__ for cls in AuditedModel.__mro__])['AuditedModel', 'ValidateInput', 'LogTraining', 'Model', 'object']Model is the root: it ends the chain. ValidateInput and LogTraining each add one step and pass control on with super(). AuditedModel contains no code. Its MRO is the plan of the whole call.
Step 2 — Follow the chain
Section titled “Step 2 — Follow the chain”print("fit():")AuditedModel().fit(X_train[:100], y_train[:100])fit(): ValidateInput.fit: checking lengths LogTraining.fit: start Model.fit: learning from 100 rows LogTraining.fit: doneThe call follows the MRO exactly. super() in ValidateInput reaches LogTraining, its sibling, not Model. LogTraining wraps the rest of the chain, so its “done” line comes after Model has learned. Model.fit runs once.
Step 3 — Watch a bad input stop the chain early
Section titled “Step 3 — Watch a bad input stop the chain early”AuditedModel().fit(X_train[:100], y_train[:99]) ValidateInput.fit: checking lengthsValueError: X has 100 rows but y has 99The check is first in the MRO, so it stops the call before any logging or learning. To check after logging starts, swap the parents: class AuditedModel(LogTraining, ValidateInput).
Step 4 — Break the chain with a hard-coded parent
Section titled “Step 4 — Break the chain with a hard-coded parent”class ValidateInputOld(Model): def fit(self, X: Rows, y: list[float]) -> Self: print(" ValidateInputOld.fit: checking lengths") return Model.fit(self, X, y) # names the parent instead of super()
class LogTrainingOld(Model): def fit(self, X: Rows, y: list[float]) -> Self: print(" LogTrainingOld.fit: start") result = Model.fit(self, X, y) print(" LogTrainingOld.fit: done") return result
class AuditedModelOld(ValidateInputOld, LogTrainingOld): pass
AuditedModelOld().fit(X_train[:100], y_train[:100]) ValidateInputOld.fit: checking lengths Model.fit: learning from 100 rowsModel.fit(self, ...) jumps straight to Model and skips the rest of the MRO, so the logging never runs and no error tells you. If you “fix” it by calling both parents by name, Model.fit runs twice. super() is the only call that visits each class once, in MRO order.
Common mistakes:
- Naming the parent (
Model.fit(self, X, y)) in a class that may be combined with others. Usesuper().fit(X, y). - Letting the root class call
super().fit().objecthas nofit(), so the chain ends inAttributeError: 'super' object has no attribute 'fit'. - Giving the methods of the chain different parameters. Each class must accept what the class before it passes on.
Example 5 — Compare models polymorphically with duck typing
Section titled “Example 5 — Compare models polymorphically with duck typing”Goal: Write one evaluation function that accepts any model, including a class from another team that inherits from nothing of yours, and find out where duck typing breaks.
Step 1 — Write a function that needs only fit and predict
Section titled “Step 1 — Write a function that needs only fit and predict”def evaluate( model: Any, X_tr: Rows, y_tr: list[float], X_te: Rows, y_te: list[float]) -> float: """Fit any model and return its test MAE.""" model.fit(X_tr, y_tr) return mae(y_te, model.predict(X_te))
for model in (BaselineRegressor(), MedianRegressor(), LinearRegression()): score = evaluate(model, X_train, y_train, X_test, y_test) print(f"{type(model).__name__:<18} MAE {score:>9,.0f}")BaselineRegressor MAE 225,400MedianRegressor MAE 219,511LinearRegression MAE 154,798evaluate() never asks what a model is. Each object brings its own fit() and predict(), and the same two lines work for all three. Adding a model to the comparison means adding one item to the tuple, not a new if branch.
Step 2 — Add a model that shares no base class
Section titled “Step 2 — Add a model that shares no base class”class PricePerSqftModel: """Another team's model: size times the median price per square foot."""
def fit(self, X: Rows, y: list[float]) -> Self: self.rate_ = median(price / row[0] for row, price in zip(X, y, strict=True)) return self
def predict(self, X: Rows) -> list[float]: return [row[0] * self.rate_ for row in X]
print([cls.__name__ for cls in PricePerSqftModel.__mro__])score = evaluate(PricePerSqftModel(), X_train, y_train, X_test, y_test)print(f"PricePerSqftModel MAE {score:>9,.0f}")['PricePerSqftModel', 'object']PricePerSqftModel MAE 158,325The class inherits only from object, and it still works. This is duck typing: evaluate() needs two methods, and the object has them.
Step 3 — See where duck typing fails
Section titled “Step 3 — See where duck typing fails”class Notes: """Not a model: it has fit() but no predict()."""
def fit(self, X: Rows, y: list[float]) -> Self: print(" Notes.fit ran") return self
evaluate(Notes(), X_train, y_train, X_test, y_test) Notes.fit ranAttributeError: 'Notes' object has no attribute 'predict'The error comes late: fit() ran first. With a real model, that may be twenty minutes of training before the crash.
Step 4 — Check the interface before the work
Section titled “Step 4 — Check the interface before the work”def has_model_api(obj: object) -> bool: return all(callable(getattr(obj, name, None)) for name in ("fit", "predict"))
for candidate in (LinearRegression(), Notes(), PricePerSqftModel()): name = type(candidate).__name__ if not has_model_api(candidate): print(f"skip {name}: it needs fit() and predict()") continue score = evaluate(candidate, X_train, y_train, X_test, y_test) print(f"{name:<18} MAE {score:>9,.0f}")LinearRegression MAE 154,798skip Notes: it needs fit() and predict()PricePerSqftModel MAE 158,325getattr(obj, name, None) returns None when the attribute is missing, and callable() checks that the attribute can be called. This LBYL check runs before any training. Examples 6 and 7 move the same check to class creation time and to type-check time.
Common mistakes:
- Dispatching on type:
if type(model) == LinearRegression: ... elif .... Every new model needs a new branch. Call the shared method and let each class decide. - Wrapping the whole
evaluate()call intry ... except AttributeError. A typo inside a model’spredict()also raisesAttributeError, and theexcepthides that real bug. - Testing
hasattr(obj, "predict")only. An attribute namedpredictthat holds a string passes. Addcallable().
Example 6 — Enforce the model contract with an ABC
Section titled “Example 6 — Enforce the model contract with an ABC”Goal: A team library has many contributors. A new model class that forgets predict() must fail when it is created, not after training. Define the contract with an ABC and give it a shared concrete method.
Step 1 — Declare the contract
Section titled “Step 1 — Declare the contract”from abc import ABC, abstractmethod
class AbstractRegressor(ABC): """Every regressor must implement fit() and predict()."""
@abstractmethod def fit(self, X: Rows, y: list[float]) -> Self: """Learn from X and y and return self."""
@abstractmethod def predict(self, X: Rows) -> list[float]: """Return one prediction per row of X."""
def fit_predict(self, X: Rows, y: list[float]) -> list[float]: return self.fit(X, y).predict(X)
print(sorted(AbstractRegressor.__abstractmethods__))['fit', 'predict']A docstring alone is a valid method body, and it documents the contract for the authors of subclasses. __abstractmethods__ is the set of names that a subclass must still implement. fit_predict() is a normal method: it works for every subclass, because it only calls the two abstract methods.
Step 2 — Try to create an incomplete model
Section titled “Step 2 — Try to create an incomplete model”class HalfDoneRegressor(AbstractRegressor): def fit(self, X: Rows, y: list[float]) -> Self: self.mean_ = mean(y) return self
print(sorted(HalfDoneRegressor.__abstractmethods__))['predict']The class itself is created without error, and __abstractmethods__ shows what is still missing. Its instances are refused:
HalfDoneRegressor()TypeError: Can't instantiate abstract class HalfDoneRegressor without an implementation for abstract method 'predict'The error comes when you create the object, before any data is touched. The message names the missing method.
Step 3 — Complete the model
Section titled “Step 3 — Complete the model”class MeanABCRegressor(AbstractRegressor): def fit(self, X: Rows, y: list[float]) -> Self: self.mean_ = mean(y) return self
def predict(self, X: Rows) -> list[float]: return [self.mean_ for _ in X]
preds = MeanABCRegressor().fit_predict(X_train[:3], y_train[:3])print([round(p) for p in preds])print(isinstance(MeanABCRegressor(), AbstractRegressor))print(sorted(MeanABCRegressor.__abstractmethods__))[602333, 602333, 602333]True[]With both methods in place, the set of abstract methods is empty, and the class can be instantiated. fit_predict() comes free from the ABC.
Step 4 — Compare with the NotImplementedError style
Section titled “Step 4 — Compare with the NotImplementedError style”class OldStyleBase: def predict(self, X: Rows) -> list[float]: raise NotImplementedError("subclasses must implement predict()")
class Forgetful(OldStyleBase): def fit(self, X: Rows, y: list[float]) -> Self: print(" fitting... (imagine 20 minutes)") return self
Forgetful().fit(X_train, y_train).predict(X_test) fitting... (imagine 20 minutes)NotImplementedError: subclasses must implement predict()Raising NotImplementedError in the base class is an older and still common style. It gives a clear message, but only when the missing method is called. The ABC moves the same error to the moment of creation.
Common mistakes:
- Using
@abstractmethodin a class that does not inherit fromABC. The decorator then does nothing, and incomplete subclasses are created without complaint. - Expecting an ABC to check signatures.
def predict(self)with noXcounts as an implementation. Only mypy (Example 7) compares signatures. - Putting
@abstractmethodabove@propertyor@classmethod. It must be the innermost decorator: write it last, just abovedef.
Example 7 — Describe the model interface with a Protocol
Section titled “Example 7 — Describe the model interface with a Protocol”Goal: A reporting function should accept any object with a predict() method, including models from libraries that you cannot change. State that requirement with a Protocol and let mypy check every call before the program runs.
Step 1 — Write the protocol and a function that uses it
Section titled “Step 1 — Write the protocol and a function that uses it”"""mypy checks that each model matches the Predictor protocol."""
from statistics import medianfrom typing import Protocol
class Predictor(Protocol): def predict(self, X: list[list[float]]) -> list[float]: ...
class MedianModel: def __init__(self, y: list[float]) -> None: self.median_ = median(y)
def predict(self, X: list[list[float]]) -> list[float]: return [self.median_ for _ in X]
class RowModel: """Predicts one row at a time: the wrong shape for Predictor."""
def predict(self, row: list[float]) -> float: return 400_000.0
def first_prediction(model: Predictor, X: list[list[float]]) -> float: return model.predict(X)[0]
X = [[1200.0], [2400.0]]print(first_prediction(MedianModel([250_000.0, 410_000.0, 376_000.0]), X))print(first_prediction(RowModel(), X))376000.0TypeError: 'float' object is not subscriptableMedianModel matches the protocol, so the first call works. RowModel has a predict() method too, but it takes one row and returns one number. The program runs into it only on the last line, and the error message talks about a float, far from the real cause.
Step 2 — Let mypy find the mismatch first
Section titled “Step 2 — Let mypy find the mismatch first”mypy --pretty predictor_check.pypredictor_check.py:32: error: Argument 1 to "first_prediction" has incompatible type "RowModel";expected "Predictor" [arg-type] print(first_prediction(RowModel(), X)) ^~~~~~~~~~predictor_check.py:32: note: Following member(s) of "RowModel" have conflicts:predictor_check.py:32: note: Expected:predictor_check.py:32: note: def predict(self, X: list[list[float]]) -> list[float]predictor_check.py:32: note: Got:predictor_check.py:32: note: def predict(self, row: list[float]) -> floatFound 1 error in 1 file (checked 1 source file)mypy reads the code without running it. It compares each argument with the parameter type. For a protocol, it compares the methods member by member, and it shows the expected and the actual signature. The --pretty flag shows the source line and wraps long messages. The bug is found before any model trains.
Step 3 — Check at run time, and see the limit
Section titled “Step 3 — Check at run time, and see the limit”@runtime_checkableclass SupportsPredict(Protocol): def predict(self, X: Rows) -> list[float]: ...
class RowModel: def predict(self, row: list[float]) -> float: return 400_000.0
for obj in (LinearRegression(), PricePerSqftModel(), RowModel(), Notes()): print(f"{type(obj).__name__:<18} {isinstance(obj, SupportsPredict)}")LinearRegression TruePricePerSqftModel TrueRowModel TrueNotes Falseisinstance() with a runtime-checkable protocol only checks that a predict attribute exists. RowModel passes, although mypy rejected it in Step 2. Rely on mypy for the real check, and treat the runtime check as a quick filter, like has_model_api() in Example 5.
Common mistakes:
- Inheriting from the protocol in every model class “to be safe”. It works, but it gives up the main benefit: classes that you cannot edit match without inheriting.
- Calling
isinstance(obj, SupportsPredict)without@runtime_checkable. It raisesTypeError: Instance and class checks can only be used with @runtime_checkable protocols. - Trusting a runtime protocol check as proof that
predict()takes the right arguments. It checks names only.
Example 8 — Choose composition for a scaled regressor
Section titled “Example 8 — Choose composition for a scaled regressor”Goal: Fit the price model on scaled sizes. The tempting design inherits from both StandardScaler and LinearRegression. See it break, then build the model with composition.
Step 1 — Inherit from both parents
Section titled “Step 1 — Inherit from both parents”class ScaledLinearRegression(StandardScaler, LinearRegression): """Is it a scaler or a regression? Both parents define fit()."""
for position, cls in enumerate(ScaledLinearRegression.__mro__): print(position, cls.__name__)bad = ScaledLinearRegression()print(bad.get_params())0 ScaledLinearRegression1 StandardScaler2 TransformerMixin3 LinearRegression4 RegressorMixin5 BaseEstimator6 object{'with_mean': True, 'with_std': True}The MRO is valid, so Python creates the class. But only one __init__ can win, and it is the scaler’s: get_params() reports with_mean and with_std, and fit_intercept is gone.
Step 2 — Fit and predict
Section titled “Step 2 — Fit and predict”bad.fit(X_train, y_train).predict(X_test)AttributeError: 'ScaledLinearRegression' object has no attribute 'intercept_'fit is found first in StandardScaler, so the object learns means and scales and never fits a line. predict is found in LinearRegression, which needs intercept_. A scaled regression is not a kind of scaler; it uses a scaler. The design fails the is-a test.
Step 3 — Compose a scaler and a regressor
Section titled “Step 3 — Compose a scaler and a regressor”class ScaledRegressor(RegressorMixin, BaseEstimator): """Scale X with a transformer, then fit a regressor on the scaled rows."""
def __init__(self, scaler: Any, regressor: Any) -> None: self.scaler = scaler # has-a transformer self.regressor = regressor # has-a regressor
def fit(self, X: Rows, y: list[float]) -> Self: self.regressor.fit(self.scaler.fit_transform(X), y) return self
def predict(self, X: Rows) -> list[float]: return self.regressor.predict(self.scaler.transform(X))
model = ScaledRegressor(StandardScaler(), LinearRegression()).fit(X_train, y_train)print(f"R² {model.score(X_test, y_test):.3f}")print(f"price change per standard deviation of sqft: {model.regressor.coef_:,.0f}")print({name: type(value).__name__ for name, value in model.get_params().items()})R² 0.561price change per standard deviation of sqft: 224,225{'scaler': 'StandardScaler', 'regressor': 'LinearRegression'}ScaledRegressor inherits only what it really is: an estimator (BaseEstimator) that is a regressor (RegressorMixin). The scaling and the line fitting are delegated to the parts. R² is the same as in Example 3: scaling one feature changes the units of coef_, not the quality of the fit. The parts are hyperparameters too, so get_params() returns them.
Step 4 — Swap a part
Section titled “Step 4 — Swap a part”for regressor in (MedianRegressor(), LinearRegression()): model = ScaledRegressor(StandardScaler(), regressor).fit(X_train, y_train) print(f"{type(regressor).__name__:<16} R² {model.score(X_test, y_test):.3f}")MedianRegressor R² -0.161LinearRegression R² 0.561Any object with fit() and predict() plugs in as the regressor, and any object with fit_transform() and transform() plugs in as the scaler. With inheritance, each combination would need its own class. The median baseline scores below 0, worse than predicting the test mean: it ignores the size, and the test houses, sold later, cost more than the training median. Module 20 grows this idea into a Pipeline with any number of named steps.
Common mistakes:
- Inheriting from two classes that both define the core method (
fithere). Only one version runs, with no warning. - Calling
self.scaler.transform(X)infit()instead offit_transform(X). The scaler has learned nothing yet and fails on the missingmean_. - Creating the parts inside
__init__(self.scaler = StandardScaler()). The user can no longer pass another part, andget_params()cannot report a choice. Take the parts as arguments.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
A child __init__ without super().__init__() |
AttributeError for an attribute that the parent sets |
Call super().__init__(...) and pass the parent’s arguments |
Naming the parent: Model.fit(self, X, y) |
In a diamond, a class is skipped or runs twice | Use super().fit(X, y) in every class of the chain |
The root class calls super().fit() |
AttributeError: 'super' object has no attribute 'fit' |
The root class ends the chain and does not call super() |
A parent listed before its own child: class C(Base, Child) |
TypeError: Cannot create a consistent method resolution order (MRO) |
List the more specific class first, or drop the redundant base |
| A mixin to the right of the base class | The mixin’s override never runs | Put mixins left: class Scaler(TransformerMixin, BaseEstimator) |
Inheriting from two classes that both define fit() |
Only one fit() runs; the object is half trained |
Use composition: hold both parts and delegate |
__init__ stores a changed value or uses **kwargs |
get_params() raises AttributeError or misses parameters |
Store each argument unchanged, under its own name |
@abstractmethod without inheriting from ABC |
Incomplete subclasses are created without error | class Base(ABC): |
| A subclass misses an abstract method | TypeError: Can't instantiate abstract class ... without an implementation for abstract method |
Implement every method in __abstractmethods__ |
isinstance() with a plain Protocol |
TypeError: Instance and class checks can only be used with @runtime_checkable protocols |
Add @runtime_checkable, or let mypy check |
Trusting isinstance(obj, SomeProtocol) |
A wrong signature or a non-callable attribute passes | Run mypy; check callable() at run time |
if type(model) == ... chains |
Every new model needs a new branch | Call the shared method: polymorphism |
type(obj) == Parent to test the family |
False for every subclass |
isinstance(obj, Parent) |
except AttributeError around a whole call |
Hides real bugs inside the method | Check the interface first, or catch only around the lookup |
| A deep hierarchy, five levels or more | A change in a parent breaks distant children | Keep two or three levels; compose the rest |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web frameworks: Django’s class-based views are built from a base
Viewand mixins.class ProductListView(LoginRequiredMixin, ListView)adds a login check, and a view overridesget_queryset()and callssuper().get_queryset()to filter the parent’s result. - Exception hierarchies: libraries define one base error and specific subclasses, so callers catch a whole family with one
except.requests.exceptions.RequestExceptionis the parent ofConnectionError,TimeoutandHTTPError. scikit-learn’sNotFittedErrorinherits from bothValueErrorandAttributeError, so old code that catches either one still works. - Plugin systems: an application defines an ABC, such as an
Exporterwith an abstractexport()method, and each plugin subclasses it. Airflow operators subclassBaseOperatorand overrideexecute(). The special class method__init_subclass__, which Python calls on a parent class each time a subclass is created, can register every plugin automatically (exercise M19-X02). pytest finds plugins by the hook functions that they define, which is duck typing. - Tooling and automation:
logginghandlers subclasslogging.Handlerand overrideemit().json.dump()writes to any object with awrite()method: a file, aStringIOobject or a network stream.
Summary
Section titled “Summary”- Inheritance builds an is-a relation:
class Child(Parent)reuses the parent’s code. Python looks up a name in the object, then its class, then the parents in MRO order. - A child inherits, replaces or extends each method. To extend, call
super().method(...). A child__init__must callsuper().__init__(). Class.__mro__lists the search order. C3 keeps children before parents and parents in the listed order, and it rejects impossible orders with aTypeError.super()means “the next class in the MRO of the object’s class”. In cooperative classes, every method callssuper()once and a root class ends the chain, so each class in a diamond runs exactly once.- A mixin adds one capability and relies on the host class. Put mixins to the left of the base class.
- A generic
BaseEstimatorreads the__init__signature withinspect.signatureto give every subclassget_params(),set_params()and cloning. - Polymorphism and duck typing let one loop work with any object that has the right methods. ABCs reject incomplete classes at creation time. Protocols describe an interface that mypy checks without inheritance;
@runtime_checkablechecks names only. - Inherit for is-a and full substitutability; compose for has-a, for swappable parts and for reuse of a few methods. When in doubt, compose.
Self-check questions
Section titled “Self-check questions”Q1. class MedianRegressor(BaselineRegressor) defines only _center(). Where does Python find fit() when you call MedianRegressor().fit(X, y), and which _center() does that fit() call?
Answer
fit() is not in MedianRegressor, so Python finds it in the next class of the MRO, BaselineRegressor. Inside it, self._center(y) starts a new search at type(self), which is MedianRegressor, so the median version runs.
Q2. A child class defines __init__(self, alpha) and sets self.alpha = alpha. The parent’s __init__ sets self.fit_intercept. What happens when you read child.fit_intercept, and how do you fix it?
Answer
AttributeError, because Python does not call the parent’s __init__ automatically. Add super().__init__(fit_intercept=fit_intercept) in the child’s __init__ and accept that argument too.
Q3. What does super() mean inside a method: “my parent class” or something else? Why does the difference matter?
Answer
It means “the next class after this one in the MRO of type(self)”. In single inheritance that is the parent. In a diamond it can be a sibling class. This is why cooperative classes visit each class exactly once, and why hard-coded parent calls skip classes or run one twice.
Q4. Write the MRO of class D(B, C) where class B(A) and class C(A). Why does A come after C?
Answer
D, B, C, A, object. B comes before C because the class statement lists it first. A comes after both B and C, because a class always comes before its parents, and A is the parent of both.
Q5. Why should a mixin be listed to the left of the main base class?
Answer
Python searches the parents in the listed order. A mixin on the left is found first, so it can override or extend a method of the base class with super(). On the right, the base class’s version is found first and the mixin’s method is silently ignored.
Q6. BaseEstimator.get_params() reads inspect.signature(cls.__init__). Why does scikit-learn forbid **kwargs in an estimator’s __init__?
Answer
get_params() builds its list of hyperparameters from the parameter names in the signature. Values that arrive through **kwargs have no name there, so get_params(), set_params() and clone() cannot see them, and tuning tools would lose them.
Q7. A class Base(ABC) has the abstract methods fit and predict. A subclass defines only fit. When does the error appear, and what is it?
Answer
When you create an instance of the subclass, not when you define it. It is TypeError: Can't instantiate abstract class Sub without an implementation for abstract method 'predict'.
Q8. What is the difference between an ABC and a Protocol? Give one case for each.
Answer
An ABC is nominal by default: a class must inherit from it (or be registered, or match a __subclasshook__, as some collections.abc classes define), and the check of abstract methods happens at instantiation. It can share concrete methods, so it suits your own class family or a plugin base class. A Protocol is structural: any class with matching methods satisfies it, without inheriting, and mypy checks it before the code runs. It suits a function parameter that must accept third-party objects.
Q9. An object has predict = "todo" as a class attribute. What does isinstance(obj, SupportsPredict) return for a @runtime_checkable protocol with a predict() method? What does this tell you?
Answer
True. The runtime check only tests that an attribute named predict exists. It does not check that it is callable or that its signature matches. Use mypy for the real check and callable() for a runtime test.
Q10. You need a model that scales its input and then fits a regression. Should ScaledRegression inherit from StandardScaler and LinearRegression, or hold them? Why?
Answer
Hold them (composition). A scaled regression is not a kind of scaler: it uses one. With inheritance, both parents define fit() and __init__(), and only one version of each wins, so the object is half trained. Composition calls each part on purpose, and you can swap either part.
Q11. Why is for model in models: print(model.score(X, y)) better than a chain of if isinstance(model, ...) branches?
Answer
It is polymorphic: each class supplies its own score(), so a new model class works without any change to the loop. The if chain must be edited for every new class, and it is easy to forget one.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 29 exercises on subclasses,
super(), the MRO, mixins,get_params(), ABCs, Protocols and composition. - Mini-project: refactor
minilearnontoBaseEstimatorand mixins, add aKNNClassifier, and compare models in one polymorphic loop. - Cheat sheet: inheritance,
super(), MRO, mixins, ABC vs Protocol and composition on one page. - Next module: 20. The Python data model teaches dunder methods such as
__repr__,__len__and__getitem__, so that your estimators and aPipelinebehave like built-in objects.