Advanced OOP, Part 1: Inheritance, MRO & ABCs
Estimator, subclass it, see how Python picks which method runs when several parents define it, turn the base into an abstract class that refuses to be built incomplete, and add three small helpers that all depend on classes. Each one attaches to the same Estimator family: a timer you use with with to time a fit, a decorator that counts predict calls, and a family of exceptions, including a NotFittedError that the models raise.Enum and Protocol.After this lesson, you will be able to:
- Subclass a base class, override a method, and extend it with super()
- Predict which method runs in a diamond hierarchy by reading __mro__
- Make a base class abstract with abc.ABC and @abstractmethod, and say when the error appears
- Write a context manager as a class with __enter__ and __exit__, and a decorator as a class with __call__
- Define a small hierarchy of custom exceptions under one base class and catch it at the right level
Before you start
#Two models with no shared contract
MeanBaseline always predicts the average label. SlopeModel fits a line through the origin. A small evaluate function trains a model and returns its root mean squared error (RMSE), the typical size of a prediction error.SlopeModel.class MeanBaseline:
def fit(self, X, y):
self.mean_ = sum(y) / len(y)
return self
def predict(self, X):
return [self.mean_ for _ in X]
class SlopeModel:
def fit(self, X, y):
# least squares through the origin: slope = sum(x*y) / sum(x*x)
self.slope_ = sum(x * t for x, t in zip(X, y)) / sum(x * x for x in X)
print("fit finished")
return self
def predicts(self, X): # typo: should be predict
return [self.slope_ * x for x in X]
def evaluate(model, X_train, y_train, X_test, y_test):
model.fit(X_train, y_train)
preds = model.predict(X_test)
mse = sum((p - t) ** 2 for p, t in zip(preds, y_test)) / len(y_test)
return mse ** 0.5
X_train, y_train = [1, 2, 3, 4], [2.1, 3.9, 6.2, 7.8]
X_test, y_test = [5, 6], [10.1, 11.8]
print(round(evaluate(MeanBaseline(), X_train, y_train, X_test, y_test), 2))
try:
print(evaluate(SlopeModel(), X_train, y_train, X_test, y_test))
except AttributeError as e:
print("AttributeError:", e)
# Output:
# 6.01
# fit finished
# AttributeError: 'SlopeModel' object has no attribute 'predict'fit has finished. On four rows that costs nothing. On a real dataset fit is the slow step, so you would wait for it and only then learn that the class was never complete. Nothing in the language connected the two classes, so nothing could check them.fit and predict" should be something Python checks. Inheritance gives you the first, and abstract base classes give you the second.#Inheritance: write the shared part once
SlopeModel is an Estimator, so inheriting makes sense. If the sentence sounds wrong, give the class an instance of the other class as an attribute instead.class Estimator:
"""Shared behaviour for every model."""
def __init__(self, name):
self.name = name
self.n_samples_ = 0
def fit(self, X, y):
self.n_samples_ = len(X) # bookkeeping every model needs
return self
def predict(self, X):
raise NotImplementedError("subclasses must override predict")
def score(self, X, y):
"""Root mean squared error, written once for every model."""
preds = self.predict(X)
mse = sum((p - t) ** 2 for p, t in zip(preds, y)) / len(y)
return mse ** 0.5
def __repr__(self):
return f"{type(self).__name__}(name={self.name!r}, n_samples={self.n_samples_})"
class MeanBaseline(Estimator):
def __init__(self):
super().__init__("mean-baseline") # run Estimator's setup first
def fit(self, X, y):
super().fit(X, y) # reuse the parent's fit, then add to it
self.mean_ = sum(y) / len(y)
return self
def predict(self, X):
return [self.mean_ for _ in X]
class SlopeModel(Estimator):
def __init__(self):
super().__init__("slope")
def fit(self, X, y):
super().fit(X, y)
self.slope_ = sum(x * t for x, t in zip(X, y)) / sum(x * x for x in X)
return self
def predict(self, X):
return [self.slope_ * x for x in X]
X_train, y_train = [1, 2, 3, 4], [2.1, 3.9, 6.2, 7.8]
X_test, y_test = [5, 6], [10.1, 11.8]
for model in [MeanBaseline(), SlopeModel()]:
model.fit(X_train, y_train)
print(model, "RMSE:", round(model.score(X_test, y_test), 3))
print(isinstance(model, Estimator), issubclass(SlopeModel, Estimator))
# Output:
# MeanBaseline(name='mean-baseline', n_samples=4) RMSE: 6.01
# SlopeModel(name='slope', n_samples=4) RMSE: 0.145
# True Truesuper() means "the parent's version of this". super().__init__("slope") runs Estimator.__init__, so name and n_samples_ exist. super().fit(X, y) inside fit runs the parent's version and then continues with what is specific to this model. That is how you extend a method rather than replace it.score is written once on Estimator, but it calls self.predict. Python looks predict up on the actual object, so each model's own override runs. A function that takes any Estimator works with every current and future subclass, which is polymorphism.predict raises NotImplementedError, which is a common way to say "override me". It protects you only when the method is called. A subclass that forgets predict still builds fine, and you hear about it at the first call, which is the same late failure as before.#Method resolution order and super()
__mro__.The list comes from an algorithm called C3 linearization. You only need its three guarantees. A class always comes before its parents. The parents keep the order you wrote them in. A shared ancestor comes after every class that inherits from it.
Component, a Scaler and a Logger each extend it, and a Step combines both. The classes only print, so the order of calls is easy to see.class Component:
def __init__(self):
print("Component.__init__")
def describe(self):
return "Component"
class Scaler(Component):
def __init__(self):
print("Scaler.__init__ start")
super().__init__()
print("Scaler.__init__ end")
def describe(self):
return "Scaler"
class Logger(Component):
def __init__(self):
print("Logger.__init__ start")
super().__init__()
print("Logger.__init__ end")
def describe(self):
return "Logger"
class Step(Scaler, Logger):
def __init__(self):
print("Step.__init__ start")
super().__init__()
print("Step.__init__ end")
print([c.__name__ for c in Step.__mro__])
step = Step()
print(step.describe())
print([c.__name__ for c in Scaler.__mro__])
# Output:
# ['Step', 'Scaler', 'Logger', 'Component', 'object']
# Step.__init__ start
# Scaler.__init__ start
# Logger.__init__ start
# Component.__init__
# Logger.__init__ end
# Scaler.__init__ end
# Step.__init__ end
# Scaler
# ['Scaler', 'Component', 'object']Scaler calls super().__init__(), and the next thing to run is Logger, not Component. Logger is not Scaler's parent. It is the next class after Scaler in the MRO of the object being built.super() really means. It is not "my parent". It is "the next class after me in the MRO of type(self)". Inside a Step, Scaler's super() goes to Logger. Inside a plain Scaler, the same line goes to Component, as the last line of output shows. Each class in the diamond ran exactly once, and Component ran last.Now predict the result of a version of the same diamond that returns lists instead of printing.
class A:
def hi(self):
return ["A"]
class B(A):
def hi(self):
return ["B"] + super().hi()
class C(A):
def hi(self):
return ["C"] + super().hi()
class D(B, C):
def hi(self):
return ["D"] + super().hi()What does D().hi() return, and what does B().hi() return on its own?
#Mixins: small capabilities you add on the side
__init__ and no data of its own. Put the mixin first in the parent list so that its methods are found before the base class.class LogMixin:
"""Adds a log() method. Knows nothing about models."""
def log(self, message):
print(f"[{type(self).__name__}] {message}")
class Estimator:
"""The same base as above, trimmed to what this cell needs."""
def __init__(self, name):
self.name = name
def fit(self, X, y):
self.mean_ = sum(y) / len(y)
return self
def predict(self, X):
return [self.mean_ for _ in X]
class LoggedBaseline(LogMixin, Estimator):
def fit(self, X, y):
self.log(f"fitting on {len(X)} rows")
return super().fit(X, y)
m = LoggedBaseline("mean")
m.fit([1, 2, 3], [2.0, 4.0, 6.0])
print(m.predict([10]))
print([c.__name__ for c in LoggedBaseline.__mro__])
# Output:
# [LoggedBaseline] fitting on 3 rows
# [4.0]
# ['LoggedBaseline', 'LogMixin', 'Estimator', 'object']__init__ runs first, a helper object stored as an attribute is usually the clearer design.super(). One class that names its parent directly breaks the chain, and Python does not warn you.class Component:
def __init__(self):
print("Component.__init__")
class Scaler(Component):
def __init__(self):
print("Scaler.__init__")
Component.__init__(self) # names the parent directly
class Logger(Component):
def __init__(self):
print("Logger.__init__")
super().__init__()
class Step(Scaler, Logger):
def __init__(self):
print("Step.__init__")
super().__init__()
Step()
# Output:
# Step.__init__
# Scaler.__init__
# Component.__init__Logger.__init__ never ran. If Logger set up a log file or a counter, Step would now be missing it, with no error until something used it. The fix is the habit from the start of this lesson: write super().__init__() and never the parent's name.Each class in this diamond adds its own name to a list when it is set up. The output is missing 'Logger'. Change one line so that every class in the MRO runs.
['Component', 'Logger', 'Scaler']
#Abstract base classes: a contract checked at construction
abc.ABC and marking the required methods with @abstractmethod. Python then refuses to create an object from any class that still has an unimplemented abstract method. This is the checked version of the NotImplementedError trick.Estimator again, now with the contract enforced, and SlopeModel with the same typo as at the start.from abc import ABC, abstractmethod
class Estimator(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def fit(self, X, y):
"""Learn from the data and return self."""
@abstractmethod
def predict(self, X):
"""Return one prediction per row of X."""
def score(self, X, y):
preds = self.predict(X)
mse = sum((p - t) ** 2 for p, t in zip(preds, y)) / len(y)
return mse ** 0.5
class SlopeModel(Estimator):
def __init__(self):
super().__init__("slope")
def fit(self, X, y):
self.slope_ = sum(x * t for x, t in zip(X, y)) / sum(x * x for x in X)
return self
def predicts(self, X): # the same typo as before
return [self.slope_ * x for x in X]
try:
Estimator("base")
except TypeError as e:
print("1:", e)
try:
SlopeModel()
except TypeError as e:
print("2:", e)
# Output:
# 1: Can't instantiate abstract class Estimator without an implementation for abstract methods 'fit', 'predict'
# 2: Can't instantiate abstract class SlopeModel without an implementation for abstract method 'predict'SlopeModel(), before fit could ever start. The wording is from Python 3.12 and later. Older versions say "with abstract methods fit, predict", and the behaviour is identical.super(), so the base can offer a default that a subclass extends.score method on the ABC is an ordinary method, so subclasses inherit it. An abstract class mixes enforced requirements with shared code, and that is its main use. One warning about the name: this score returns an error, so lower is better, while scikit-learn's score returns a value where higher is better.Child inherits from an ABC that declares an abstract predict, and Child defines predicts instead. When does Python first complain?
nn.Module is not an abstract base class: it expects you to define forward(), and a module without one fails with NotImplementedError when it is called. scikit-learn's LinearRegression().predict(...) before fit raises a NotFittedError, which you will build yourself in a moment. Use an ABC when you want the mistake to appear at construction.collections.abc. If you subclass MutableSequence and implement the few required methods, you get append, pop, reverse and in for free. The lesson "Python's Data Model, Part 2" covers the double-underscore methods behind such classes.#Timing a fit with a context-manager class
fit is the slow step of your SlopeModel, so you will want to time it. A context manager is an object you can put after with. Python calls its __enter__ method when the block starts and binds the return value to the name after as. It calls __exit__ when the block ends, whether the block finished normally or raised. The earlier lesson built these with a generator and @contextmanager. Written as a class, the same protocol is two methods.The names that start and end with two underscores are methods Python calls itself when you use certain syntax. You only define them here.
import time
class Timer:
"""Times the block under `with` and keeps the result."""
def __init__(self, label):
self.label = label
self.elapsed = None
def __enter__(self):
self.start = time.perf_counter()
return self # what `as t` receives
def __exit__(self, exc_type, exc_value, traceback):
self.elapsed = time.perf_counter() - self.start
status = "failed" if exc_type else "finished"
print(f"{self.label} {status}")
return False # never swallow the exception
class SlopeModel:
"""The model from above, trimmed to its fit."""
def fit(self, X, y):
self.slope_ = sum(x * t for x, t in zip(X, y)) / sum(x * x for x in X)
return self
X = list(range(1, 200_001))
y = [2 * x for x in X]
with Timer("fit") as t:
model = SlopeModel().fit(X, y)
print(model.slope_, type(t.elapsed).__name__, t.elapsed < 5)
try:
with Timer("fit on a zero column") as t2:
SlopeModel().fit([0, 0, 0], [1.0, 2.0, 3.0])
except ZeroDivisionError as e:
print("caught:", e, "| elapsed recorded:", t2.elapsed is not None)
# Output:
# fit finished
# 2.0 float True
# fit on a zero column failed
# caught: float division by zero | elapsed recorded: True__exit__ receives three arguments: the exception type, the exception, and the traceback. All three are None when the block finished cleanly, which is how Timer chooses between "finished" and "failed".__exit__ returns decides the exception's fate. False or None lets the exception continue after the cleanup, which is almost always what you want. Returning True swallows it and the program carries on after the with block, so only do that for one named exception type.t.elapsed), more methods, or needs to be reused and subclassed. For a short set-up and tear-down around one yield, @contextmanager is less code.#Class-based decorators
__call__ can be called like a function. This one counts how many times a function runs. First it counts calls to rmse, the error formula that Estimator.score uses.from functools import update_wrapper
class CountCalls:
def __init__(self, func):
update_wrapper(self, func) # copy __name__ and __doc__ onto the instance
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
@CountCalls
def rmse(preds, targets):
"""Root mean squared error."""
mse = sum((p - t) ** 2 for p, t in zip(preds, targets)) / len(targets)
return mse ** 0.5
print(round(rmse([1, 2], [1, 4]), 3))
print(round(rmse([0, 0], [3, 4]), 3))
print(rmse.calls, rmse.__name__)
# Output:
# 1.414
# 3.536
# 2 rmse@CountCalls above def rmse means rmse = CountCalls(rmse). The name rmse now refers to a CountCalls object, and calling it runs __call__. That is why rmse.calls can be read from outside, with no closure and no attribute pinned onto a wrapper. update_wrapper plays the role that @wraps plays for function decorators.predict, which is a method. Put the same decorator on it and it fails.from functools import update_wrapper
class CountCalls:
def __init__(self, func):
update_wrapper(self, func)
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
class SlopeModel:
def __init__(self):
self.slope_ = 2.0
@CountCalls
def predict(self, X):
return [self.slope_ * x for x in X]
try:
SlopeModel().predict([3])
except TypeError as e:
print("TypeError:", e)
# Output:
# TypeError: SlopeModel.predict() missing 1 required positional argument: 'X'self. A CountCalls object is an instance of a class, not a function, so Python does not bind self, and [3] lands in the self slot while X is left empty.CountCalls called __get__, and the lesson "Python's Data Model, Part 2" teaches it in its section "Descriptors: how a method gets self". For now the rule is practical: use a class-based decorator on plain functions, and use a function decorator for methods.from functools import wraps
def count_calls(func):
@wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
class SlopeModel:
def __init__(self):
self.slope_ = 2.0
@count_calls
def predict(self, X):
return [self.slope_ * x for x in X]
print(SlopeModel().predict([3]), SlopeModel.predict.calls)
# Output:
# [6.0] 1Reach for the class form when a decorator has state that outsiders read or several cooperating methods. Otherwise the function form is shorter.
#Custom exceptions: a small hierarchy
ValueError("bad") into a name that says what went wrong and that callers can catch precisely. The pattern is a base class for your project and a subclass for each kind of failure. Here the family joins the Estimator from the abstract-class section, and SlopeModel raises the errors.from abc import ABC, abstractmethod
class ModelError(Exception):
"""Base class for every error our model code raises on purpose."""
class NotFittedError(ModelError):
"""predict() or score() was called before fit()."""
class ShapeError(ModelError):
"""X and y do not line up."""
def __init__(self, n_rows, n_labels):
self.n_rows = n_rows
self.n_labels = n_labels
super().__init__(f"X has {n_rows} rows but y has {n_labels} labels")
class Estimator(ABC):
@abstractmethod
def fit(self, X, y): ...
@abstractmethod
def predict(self, X): ...
class SlopeModel(Estimator):
def fit(self, X, y):
if len(X) != len(y):
raise ShapeError(len(X), len(y))
self.slope_ = sum(x * t for x, t in zip(X, y)) / sum(x * x for x in X)
return self
def predict(self, X):
if not hasattr(self, "slope_"):
raise NotFittedError("call fit() before predict()")
return [self.slope_ * x for x in X]
for action in ["predict first", "bad shapes", "fine"]:
model = SlopeModel()
try:
if action == "predict first":
model.predict([1, 2])
elif action == "bad shapes":
model.fit([1, 2, 3], [2.0, 4.0])
else:
print(model.fit([1, 2], [2.0, 4.0]).predict([3]))
except ShapeError as e:
print("ShapeError:", e, "|", e.n_rows, e.n_labels)
except ModelError as e: # any other error from our own family
print(type(e).__name__ + ":", e)
print(issubclass(NotFittedError, ModelError), issubclass(NotFittedError, ValueError))
# Output:
# NotFittedError: call fit() before predict()
# ShapeError: X has 3 rows but y has 2 labels | 3 2
# [6.0]
# True FalseModelError adds nothing but a name, which is often enough. It earns its place because one except ModelError catches the whole family, while a KeyError or a TypeError from a real bug still passes through. ShapeError shows the other reason to write a class: it keeps n_rows and n_labels as attributes, so a handler can use the numbers without parsing the message, and super().__init__(...) passes a readable message up.except clauses matters. Python takes the first one that matches, so the specific subclass goes before its base. Put ModelError first and the ShapeError clause can never run.Exception, never from BaseException. BaseException also covers KeyboardInterrupt and SystemExit, which ordinary except clauses should not catch.#Common mistakes
These three are the ones that cost people the most time. Each block runs, so you can change it.
#Try it: finish the family
Estimator and the two exceptions. You write a MedianBaseline that predicts the median label, raises NotFittedError when predict is called before fit, and a Timer you use around fit.Tests: Expected output: the NotFittedError line, then 'fit done', median 5.05, RMSE 5.961, 'timed: True' and 'Estimator is abstract'. Then try deleting predict from MedianBaseline and see which line fails.
LogMixin to MedianBaseline and call self.log(...) from fit. Check MedianBaseline.__mro__ to see where the mixin sits.#Recap
super() calls the next class in the method resolution order of the actual object, which is the parent in a single chain and a sibling in a diamond. __mro__ shows the order, and every class that should take part in the chain has to call super() itself.predict" into a rule Python checks when you create an object. A class with __enter__ and __exit__ is a context manager with state. A class with __call__ is a decorator with state, but it is not bound to self, so use a function decorator on methods. A shared base exception such as ModelError lets one except catch your own errors while real bugs still surface.#Going further
@dataclass, Enum, Protocol and __slots__, the data side of classes. The lesson "Python's Data Model, Part 2" explains the double-underscore methods used here, and its section "Descriptors: how a method gets self" shows why @CountCalls fails on a method and how to fix it.Classes `B(A)` and `C(A)` each define `hi()` as their letter plus `super().hi()`, `A.hi()` returns the letter A, and `class D(C, B)` defines nothing. What does `D().hi()` return?