18. Classes and objects
Part 3 is about object-oriented programming. Until now, your data lived in dicts and lists, and your logic lived in separate functions. In this module, you put the data and the functions that work on it together in one unit: a class. You model sensor readings, customer records and datasets as objects. You also start minilearn, a tiny machine learning library in the style of scikit-learn, which you grow through modules 18 to 22.
What you will learn
Section titled “What you will learn”- Explain the words class, instance, attribute and method, define a class with
__init__and create objects from it. - Explain what
selfis and how Python looks up an attribute: first in the instance namespace, then in the class namespace. - Choose between instance attributes and class attributes, and avoid the shared mutable class attribute bug.
- Write instance methods,
@classmethodalternative constructors such asDataset.from_csv()and@staticmethodhelpers. - Use
@propertyfor computed attributes and for validation, such asn_neighbors > 0. - Apply Python’s encapsulation conventions:
_x,__x(name mangling) and the trailing underscore of scikit-learn’s learned attributes.
Prerequisites
Section titled “Prerequisites”- Part 2 of the course, checked with the Part 2 checkpoint.
- Functions, parameters, namespaces and docstrings: 05. Functions.
- Type hints, including
X | Noneand built-in generics such aslist[float]: 12. Type hints. - Raising exceptions and custom exception classes: 06. Errors and debugging.
- Reading CSV files with
csv.DictReader: 07. Files and data formats.
Concepts
Section titled “Concepts”Why classes: data and behavior together
Section titled “Why classes: data and behavior together”Here is one sensor reading from data/sensors.csv as a dict, with a function that works on it:
reading = {"sensor_id": "S4", "temperature_c": 24.52, "vibration_mm_s": 2.17}
def to_fahrenheit(reading: dict) -> float: return reading["temperature_c"] * 9 / 5 + 32
print(round(to_fahrenheit(reading), 2))76.14This works for one script. It gets hard to manage as the code grows:
- Nothing says which keys a reading must have. A typo such as
"temprature_c"fails only when a function reads it. - The functions that belong to readings are spread over the code. A reader cannot see them in one place.
- A machine learning model has state: the values that it stores and changes over time, such as the mean that a scaler learns. With dicts, you pass this state from function to function by hand.
Object-oriented programming (OOP) solves these problems. It groups data and the functions that use the data into objects. Module 01 said that every value in Python is an object. Now you make your own kinds of objects.
- A class is a blueprint for objects. It says which data each object holds and what each object can do.
SensorReadingis a class. - An instance is one object made from a class. The reading of sensor S4 at midnight is an instance of
SensorReading. “Object” and “instance” mean the same thing; “instance of X” says which class it comes from. - An attribute is a name stored on an object, such as
reading.temperature_c. Attributes hold the state. - A method is a function defined in a class. You call it on an instance:
reading.to_fahrenheit(). Methods are the behavior.
You have used classes since module 01. str, list and dict are classes. "S4".lower() calls the method lower of a str instance. The tools of the rest of the course are classes too:
| Object | Its state (attributes) | Its behavior (methods) |
|---|---|---|
pathlib.Path("data/sales.csv") |
the parts of the path | .exists(), .read_text() |
a pandas DataFrame |
the columns and the index | .groupby(), .to_csv() |
scikit-learn StandardScaler() |
mean_ and scale_ after fit |
.fit(), .transform() |
PyTorch nn.Linear(3, 1) |
the weights and the bias | .forward(), .parameters() |
Defining a class and creating instances
Section titled “Defining a class and creating instances”A class statement defines a class. The indented block under it is the class body. Inside the body, def defines the methods.
class SensorReading: """One row of data/sensors.csv."""
def __init__(self, sensor_id: str, temperature_c: float, vibration_mm_s: float): self.sensor_id = sensor_id self.temperature_c = temperature_c self.vibration_mm_s = vibration_mm_s
def to_fahrenheit(self) -> float: return self.temperature_c * 9 / 5 + 32
r1 = SensorReading("S1", 20.21, 2.5)r2 = SensorReading("S4", 24.52, 2.17)print(r1.sensor_id, r1.temperature_c, round(r1.to_fahrenheit(), 2))print(r2.sensor_id, r2.temperature_c, round(r2.to_fahrenheit(), 2))S1 20.21 68.38S4 24.52 76.14What happens, line by line:
class SensorReading:creates a class object and binds it to the nameSensorReading. PEP 8 writes class names in CapWords (also called PascalCase): each word starts with a capital letter and there are no underscores.- The string under the
classline is the class docstring, as for a function. SensorReading("S1", 20.21, 2.5)instantiates the class: it creates a new instance. Python first makes an empty object, then calls__init__on it with your arguments.__init__is the initializer. It sets the starting attributes of the new object. People often call it “the constructor”, which is close enough. Strictly, the callSensorReading(...)is the constructor call, and__init__fills in the object after Python has created it.__init__must returnNone.self.sensor_id = sensor_idcreates an instance attribute: a name stored on this one object.
Names such as __init__ start and end with two underscores. Module 08 called them dunder names (“double underscore”). Python calls dunder methods for you at special moments. Module 20 covers many of them.
Each call creates a separate object with its own attributes:
print(type(r1))print(isinstance(r1, SensorReading), isinstance("S1", SensorReading))print(r1 is r2)r1.temperature_c = 21.0print(r1.temperature_c, r2.temperature_c)<class '__main__.SensorReading'>True FalseFalse21.0 24.52type() shows the class. __main__ is the name of the module that runs as the script (module 08). isinstance(obj, cls) checks if an object is an instance of a class (or of a subclass of it). A change to r1 does not touch r2.
A class is also a type, so you can use it in type hints like int or str:
def mean_temperature(readings: list[SensorReading]) -> float: return sum(r.temperature_c for r in readings) / len(readings)
print(round(mean_temperature([r1, r2]), 2))22.76self: the instance a method works on
Section titled “self: the instance a method works on”A method needs to know which object it works on. Python passes that object as the first argument. By convention, the first parameter is named self.
When you write r2.to_fahrenheit(), Python finds to_fahrenheit in the class and calls SensorReading.to_fahrenheit(r2). The two calls below are the same:
print(r2.to_fahrenheit())print(SensorReading.to_fahrenheit(r2))76.13676.136So self is not magic. It is an ordinary parameter that receives the instance before the dot. Inside the method, self.temperature_c reads the attribute of that instance. For r2, self is r2.
r2.to_fahrenheit, without the parentheses, is a bound method: the function plus the instance that it is bound to. You can store it and call it later, like any function (module 05):
convert = r2.to_fahrenheitprint(convert())76.136If you forget self in the def line, Python still passes the instance, and the call fails:
class BrokenReading: def __init__(self, temperature_c: float): self.temperature_c = temperature_c
def to_fahrenheit(): # no self return 0.0
BrokenReading(21.0).to_fahrenheit()TypeError: BrokenReading.to_fahrenheit() takes 0 positional arguments but 1 was given“1 was given” looks wrong, because you passed nothing. The one argument is the instance. Read this message as “you forgot self”.
Every object stores its instance attributes in a dict, its instance namespace (module 21 shows __slots__, which replaces this dict to save memory). The class has its own namespace too, the class namespace, which holds the methods and the class attributes. vars(obj) returns the instance namespace (it is the same dict as obj.__dict__):
print(vars(r2))print([name for name in vars(SensorReading) if not name.startswith("__")]){'sensor_id': 'S4', 'temperature_c': 24.52, 'vibration_mm_s': 2.17}['to_fahrenheit']The instance holds only its data. The method lives once, in the class, and all instances share it. Each instance knows its class through its __class__ attribute.
flowchart LR
subgraph CLS["class namespace: vars(SensorReading)"]
direction TB
M1["__init__ (function)"]
M2["to_fahrenheit (function)"]
end
subgraph I1["instance namespace: vars(r1)"]
direction TB
A1["sensor_id = 'S1'"]
A2["temperature_c = 21.0"]
A3["vibration_mm_s = 2.5"]
end
subgraph I2["instance namespace: vars(r2)"]
direction TB
B1["sensor_id = 'S4'"]
B2["temperature_c = 24.52"]
B3["vibration_mm_s = 2.17"]
end
I1 -- "__class__" --> CLS
I2 -- "__class__" --> CLS
When you read obj.name, Python searches in this order:
flowchart TD
Q["read r2.name"] --> S1{"name in vars(r2)?"}
S1 -- yes --> R1["use the instance value"]
S1 -- no --> S2{"name in vars(SensorReading)?"}
S2 -- yes --> R2["use the class value<br/>(a function becomes a bound method)"]
S2 -- no --> E["AttributeError"]
The instance comes first, then the class. If neither has the name, you get an AttributeError. This picture is simplified in two ways: a @property on the class wins over the instance (see Properties), and module 19 adds the base classes to the search.
Instance attributes and class attributes
Section titled “Instance attributes and class attributes”An assignment in the class body, outside any method, creates a class attribute. It lives in the class namespace, so all instances share one value. Use class attributes for constants and defaults that are the same for every instance, such as the alert thresholds from the data/sensors.csv status rule:
class Reading: unit = "°C" # class attribute: shared by all readings warn_vibration = 4.5 # mm/s, from the sensor status rule
def __init__(self, sensor_id: str, vibration_mm_s: float): self.sensor_id = sensor_id # instance attribute: one per reading self.vibration_mm_s = vibration_mm_s
def is_warning(self) -> bool: return self.vibration_mm_s >= self.warn_vibration
a = Reading("S4", 4.54)b = Reading("S2", 2.39)print(a.unit, b.unit, Reading.unit)print(a.is_warning(), b.is_warning())°C °C °CTrue Falsea.unit is not in vars(a), so the lookup falls back to the class. self.warn_vibration works the same way inside a method.
Reading through an instance falls back to the class. Assigning through an instance does not: it creates a new instance attribute with the same name. The instance attribute shadows (hides) the class attribute for that one instance:
a.warn_vibration = 5.0 # creates an instance attribute on a onlyprint(a.is_warning(), vars(a))Reading.warn_vibration = 2.0 # changes the shared class attributeprint(a.warn_vibration, b.warn_vibration, b.is_warning())False {'sensor_id': 'S4', 'vibration_mm_s': 4.54, 'warn_vibration': 5.0}5.0 2.0 TrueAfter the class attribute changes to 2.0, b sees the new value, because it has no attribute of its own. a keeps 5.0, because its own attribute shadows the class one.
To make a class attribute explicit in a type hint, annotate it with ClassVar from the typing module. A type checker such as mypy then reports code that assigns it through an instance, and dataclasses (module 21) skip it when they build __init__:
from typing import ClassVar
class Gateway: unit: ClassVar[str] = "°C" # one value for the class max_batch: ClassVar[int] = 500 # rows per upload
def __init__(self, gateway_id: str): self.gateway_id = gateway_id # one value per instance
print(Gateway.unit, Gateway("G1").max_batch, vars(Gateway("G2")))°C 500 {'gateway_id': 'G2'}| Instance attribute | Class attribute | |
|---|---|---|
| Created by | self.name = value, usually in __init__ |
name = value in the class body |
| Stored in | vars(obj), one per instance |
vars(Cls), one for the class |
| Shared | no | yes, by every instance that does not shadow it |
| Typical use | the data of one object: an id, a reading, learned weights | constants, defaults, counters, metadata |
| Change it with | obj.name = value |
Cls.name = value |
The shared mutable class attribute gotcha
Section titled “The shared mutable class attribute gotcha”Class attributes are safe for immutable values such as numbers and strings, because an assignment never changes the shared value; it only creates an instance attribute. A mutable class attribute, such as a list or a dict, is a trap. A method that calls self.runs.append(...) does not assign to self.runs. It finds the one shared list on the class and changes it in place:
class Experiment: runs = [] # BUG: one list for every experiment
def __init__(self, name: str): self.name = name
def log_run(self, score: float) -> None: self.runs.append(score)
churn = Experiment("churn")prices = Experiment("prices")churn.log_run(0.81)prices.log_run(0.79)print(churn.runs, prices.runs, churn.runs is prices.runs)[0.81, 0.79] [0.81, 0.79] TrueThe churn experiment shows the score of the price experiment. Both names lead to the same list object. This is the class version of the mutable default argument bug of module 13. The fix is to create a new list for each instance in __init__:
class Experiment: def __init__(self, name: str): self.name = name self.runs: list[float] = [] # a new list for each experiment
def log_run(self, score: float) -> None: self.runs.append(score)
churn = Experiment("churn")prices = Experiment("prices")churn.log_run(0.81)prices.log_run(0.79)print(churn.runs, prices.runs, churn.runs is prices.runs)[0.81] [0.79] FalseA shared counter has the opposite problem. To count every instance, change the class attribute through the class. self.count += 1 reads the class value and then writes a new instance attribute, so the class counter never moves:
class Model: created = 0 # how many models exist
def __init__(self, name: str): self.name = name Model.created += 1 # change the class attribute, not self.created
m1, m2 = Model("knn"), Model("linear")print(Model.created, m1.created, "created" in vars(m1))2 2 FalseMethods
Section titled “Methods”A method can do three kinds of work:
- Return a new value and leave the object unchanged, such as
to_fahrenheit(). - Change the state of the object, such as
log_run(), which appends toself.runs. - Answer a question about the object, such as
is_warning(), which returns abool.
A method can call other methods of the same object through self. A method that changes the state can return self, so you can chain the next call on the result. scikit-learn’s fit() returns self for this reason: StandardScaler().fit(X).transform(X) is one expression. You use the same rule in minilearn.
class Thermometer: def __init__(self, offset_c: float = 0.0): self.offset_c = offset_c # calibration offset, in °C
def calibrate(self, reference_c: float, measured_c: float) -> "Thermometer": self.offset_c = round(reference_c - measured_c, 2) return self # allows chaining
def correct(self, measured_c: float) -> float: return round(measured_c + self.offset_c, 2)
def correct_all(self, readings: list[float]) -> list[float]: return [self.correct(r) for r in readings] # one method calls another
s3 = Thermometer().calibrate(reference_c=21.0, measured_c=21.35)print(s3.offset_c, s3.correct_all([21.35, 22.1, 25.85]))-0.35 [21.0, 21.75, 25.5]The return annotation "Thermometer" is in quotes. Python 3.12 and 3.13 evaluate an annotation when they run the def line. At that moment the class is not finished, so the name Thermometer does not exist yet, and -> Thermometer raises a NameError. A string annotation is not evaluated, so it works. A type hint written as a string is called a forward reference. (Python 3.14 delays the evaluation, but the quotes work in every version.) The next section shows typing.Self, which is the better tool.
@classmethod: alternative constructors
Section titled “@classmethod: alternative constructors”__init__ should take clean values: a str id and float readings. Real data arrives in other shapes: a row of text from a CSV file, a JSON dict, a line of a log. You want one place that turns each shape into an object.
A class method is a method that receives the class, not an instance, as its first argument. You make one with the @classmethod decorator (decorators are module 11). By convention, the first parameter is named cls. Its main use is an alternative constructor: a class method that builds an instance from another kind of input and returns it.
A static method, made with @staticmethod, receives neither the instance nor the class. It is a plain function that lives in the class because it belongs to the topic of the class. Here, _parse_float turns a cell of text into a float or None:
import csvfrom typing import Self
class SensorReading: def __init__( self, timestamp: str, sensor_id: str, temperature_c: float | None, vibration_mm_s: float | None, ): self.timestamp = timestamp self.sensor_id = sensor_id self.temperature_c = temperature_c self.vibration_mm_s = vibration_mm_s
@staticmethod def _parse_float(text: str) -> float | None: """Return the number in a CSV cell, or None for a blank cell.""" return float(text) if text.strip() else None
@classmethod def from_csv_row(cls, row: dict[str, str]) -> Self: """Build a reading from one row of csv.DictReader.""" return cls( timestamp=row["timestamp"], sensor_id=row["sensor_id"], temperature_c=cls._parse_float(row["temperature_c"]), vibration_mm_s=cls._parse_float(row["vibration_mm_s"]), )
with open("data/sensors.csv", newline="", encoding="utf-8") as f: readings = [SensorReading.from_csv_row(row) for row in csv.DictReader(f)]
print(len(readings))first = readings[0]print(first.timestamp, first.sensor_id, first.temperature_c, first.vibration_mm_s)gap = readings[327]print(gap.timestamp, gap.sensor_id, gap.temperature_c, gap.vibration_mm_s)80642024-05-01T00:00:00 S1 20.21 2.52024-05-01T13:30:00 S4 27.43 NoneWhat each part does:
SensorReading.from_csv_row(row)calls the class method. Python passesSensorReadingascls.cls(...)calls the class, which is the normal constructor call. So the class method ends in__init__, and every object goes through the same initializer.Self, from thetypingmodule, is the type hint for “an instance of this class”. It needs no quotes. Use it for alternative constructors and for methods that returnself.cls._parse_float(...)calls the static method. You can call it through the class or through an instance.- Row 327 has a blank vibration cell. The static method turns it into
None, the missing value of module 01.
Why cls(...) and not SensorReading(...)? With cls, a subclass that inherits from_csv_row builds an instance of the subclass. Module 19 shows this.
You have used alternative constructors already. They are all class methods:
| Call | Builds |
|---|---|
dict.fromkeys(["S1", "S2"], 0) |
{'S1': 0, 'S2': 0} |
datetime.fromisoformat("2024-05-01T13:30:00") |
a datetime from an ISO string |
int.from_bytes(b"\x01\x00", "big") |
256 from raw bytes |
pd.DataFrame.from_records(rows) |
a DataFrame from a list of dicts or tuples |
The three kinds of methods side by side:
| Instance method | Class method | Static method | |
|---|---|---|---|
| Decorator | none | @classmethod |
@staticmethod |
| First parameter | self, the instance |
cls, the class |
none |
| Can read instance state | yes | no | no |
| Can read class attributes | yes, through self |
yes, through cls |
only by naming the class |
| Typical use | the behavior of one object | alternative constructors, class-wide settings | a helper that belongs to the topic of the class |
| Example | reading.to_fahrenheit() |
SensorReading.from_csv_row(row) |
SensorReading._parse_float("2.5") |
@property: computed attributes and validation
Section titled “@property: computed attributes and validation”Some values of an object are not stored; they are computed from other attributes. The temperature in °F is one. You could write a method, reading.temperature_f(). A property lets the caller write reading.temperature_f instead, without parentheses, while Python runs a method behind the scenes.
class Reading: def __init__(self, sensor_id: str, temperature_c: float): self.sensor_id = sensor_id self.temperature_c = temperature_c
@property def temperature_f(self) -> float: """The temperature in °F, computed from temperature_c.""" return round(self.temperature_c * 9 / 5 + 32, 2)
r = Reading("S4", 24.52)print(r.temperature_f)r.temperature_c = 30.0print(r.temperature_f)76.1486.0The property always agrees with temperature_c, because it is computed on every read. A stored °F attribute would be wrong after temperature_c changes. A property with only a getter (the method that returns the value) is read-only:
r.temperature_f = 100.0AttributeError: property 'temperature_f' of 'Reading' object has no setterThe second use of a property is validation: checking a value before you accept it. Settings objects need it most. A shop shows the n_neighbors products that are most similar to the one on screen. This is the idea of k-nearest neighbors (KNN): find the k closest points and use them. A count of similar products must be a whole number of at least 1. A setter, made with @name.setter, runs on every assignment and can reject a bad value:
class RecommenderSettings: """Settings of a "similar products" box on a product page."""
def __init__(self, n_neighbors: int = 5): self.n_neighbors = n_neighbors # runs the setter below
@property def n_neighbors(self) -> int: return self._n_neighbors
@n_neighbors.setter def n_neighbors(self, value: int) -> None: if isinstance(value, bool) or not isinstance(value, int): raise TypeError(f"n_neighbors must be an int, got {type(value).__name__}") if value < 1: raise ValueError(f"n_neighbors must be >= 1, got {value}") self._n_neighbors = value
settings = RecommenderSettings(n_neighbors=3)print(settings.n_neighbors, vars(settings))settings.n_neighbors = 7print(settings.n_neighbors)3 {'_n_neighbors': 3}7RecommenderSettings(n_neighbors=0)ValueError: n_neighbors must be >= 1, got 0How it works:
@propertyturns the getter into a property object namedn_neighborson the class.@n_neighbors.setteradds the setter to that same property. Both methods must have the same name.- The value is stored in
self._n_neighbors, under another name. If the setter wroteself.n_neighbors = value, it would call itself again and again, until aRecursionError. - A property lives on the class, but it wins over the instance namespace. So
self.n_neighbors = n_neighborsin__init__runs the setter instead of creating an instance attribute. The constructor and every later assignment use the same check. boolis a subclass ofint, soisinstance(True, int)isTrue. The setter rejectsTrueexplicitly;RecommenderSettings(n_neighbors=True)is almost surely a mistake.
Encapsulation: _x, _x and x
Section titled “Encapsulation: _x, _x and x”Encapsulation means that an object hides its internal details behind a small public interface: the attributes and methods that other code is meant to use. Code that uses only the interface keeps working when the internals change.
Python has no private keyword, as Java or C++ have. Every attribute can be read and changed from outside. Python relies on naming conventions instead:
| Name | Meaning | Enforced by Python? |
|---|---|---|
name |
public: part of the interface | — |
_name |
internal: “do not use this from outside” | no; only a convention. Linters and editors respect it, and from module import * skips module-level _names |
__name |
name mangling: Python renames it to _ClassName__name |
the renaming, yes; privacy, no |
__name__ |
a dunder name that Python defines, such as __init__ |
never mangled; do not invent new ones |
name_ |
scikit-learn: a learned attribute, set by fit(), such as mean_ or coef_ |
no; only a convention |
class_, type_ |
PEP 8: a trailing underscore avoids a clash with a keyword or built-in | — |
Use _name for anything that is not part of the interface: helper methods such as _parse_float and stored values behind a property such as _n_neighbors. The single underscore says “internal” to every reader, and costs nothing.
Name mangling is a rename at compile time. When Python compiles a class body, it rewrites every identifier of the form __name (two or more leading underscores, at most one trailing underscore) to _ClassName__name. This includes the names inside the methods:
class Splitter: def __init__(self, seed: int): self.__seed = seed # stored as _Splitter__seed
def describe(self) -> str: return f"seed={self.__seed}" # also rewritten, so it finds the value
split = Splitter(42)print(vars(split))print(split.describe(), split._Splitter__seed){'_Splitter__seed': 42}seed=42 42print(split.__seed)AttributeError: 'Splitter' object has no attribute '__seed'Outside the class body, split.__seed is not rewritten, so Python looks for the literal name __seed and fails. Anyone can still read split._Splitter__seed. Name mangling is not a security feature.
Its real purpose is to avoid name clashes between a class and its subclasses (module 06 made subclasses of exceptions; module 19 covers them fully). If a base class and a subclass both use self.__calls, mangling gives them two separate attributes:
class Counter: def __init__(self): self.__calls = 0 # becomes _Counter__calls
def tick(self) -> None: self.__calls += 1
class TimedCounter(Counter): # a subclass of Counter def __init__(self): super().__init__() # run Counter.__init__ too (module 19) self.__calls = "not a number" # becomes _TimedCounter__calls
t = TimedCounter()t.tick()print(vars(t)){'_Counter__calls': 1, '_TimedCounter__calls': 'not a number'}tick() still works, because each class sees its own attribute. Without mangling, the subclass would have overwritten the counter with a string and tick() would crash. Two more facts:
- Mangling rewrites identifiers in the code, not strings.
getattr(self, "__seed")looks for the literal name__seedand fails, even inside the class. It also rewritesother.__seedinside the class, for any objectother. - Use
__namerarely: in a base class that others will subclass, for an attribute whose name a subclass might reuse. For everything else, one underscore is enough.
Classes outside data science
Section titled “Classes outside data science”The same ideas run most Python software:
- Web request objects. A web framework turns each HTTP request into an object. In FastAPI and Starlette,
request.methodis"GET"or"POST",request.url.pathis the path andrequest.headersis a dict-like object. Flask and Django have similar request classes. - Database models. In Django, each class is a database table, and each class attribute declares a column. Each instance is one row.
- Data validation models. pydantic (used by FastAPI) reads the type hints of the class attributes and validates every new instance.
- Game entities. A game keeps a
PlayerorEnemyobject per character, with state (position, health) and behavior (move(),take_damage()).
A Django model, for reading only (Django is not part of the course environment):
from django.db import models
class Customer(models.Model): # one table customer_id = models.CharField(max_length=6, unique=True) # one column plan = models.CharField(max_length=10) tenure_months = models.PositiveIntegerField() monthly_charges = models.DecimalField(max_digits=7, decimal_places=2)
def is_new(self) -> bool: # behavior for one row return self.tenure_months <= 6pydantic is installed with the course packages, so this one runs. The class attributes with type hints become validated fields:
from pydantic import BaseModel, Field, ValidationError
class CustomerIn(BaseModel): customer_id: str tenure_months: int = Field(ge=0) # ge: greater than or equal to monthly_charges: float = Field(gt=0) # gt: greater than
ok = CustomerIn(customer_id="C03991", tenure_months="6", monthly_charges=30.93)print(ok.customer_id, ok.tenure_months, type(ok.tenure_months).__name__)try: CustomerIn(customer_id="C00010", tenure_months=-1, monthly_charges=0)except ValidationError as exc: for error in exc.errors(): print(error["loc"], error["msg"])C03991 6 int('tenure_months',) Input should be greater than or equal to 0('monthly_charges',) Input should be greater than 0pydantic converted the text "6" to the int 6 and rejected two bad values in one go. You build a model like this for a prediction API in module 44. Here, notice that it is still a class with attributes and an initializer; the library writes the validating __init__ for you.
Worked examples
Section titled “Worked examples”Example 1 — Recompute sensor status with objects
Section titled “Example 1 — Recompute sensor status with objects”Goal: data/sensors.csv has a status column (ok, warn or fail). Model each row as an object, recompute the status from the documented rule and check how often the file agrees.
Step 1 — Write the class
Section titled “Step 1 — Write the class”import csvfrom collections import Counterfrom typing import Self
class SensorReading: """One 10-minute reading from data/sensors.csv."""
# Status thresholds from the sensor data sheet (shared by every reading). warn_temp_c = 33.0 fail_temp_c = 42.0 warn_vibration = 4.5 # mm/s fail_vibration = 11.2
def __init__( self, sensor_id: str, temperature_c: float | None, vibration_mm_s: float | None, status: str, ): self.sensor_id = sensor_id self.temperature_c = temperature_c self.vibration_mm_s = vibration_mm_s self.status = status # the value stored in the file
@staticmethod def _over(value: float | None, limit: float) -> bool: return value is not None and value >= limit
def computed_status(self) -> str: t, v = self.temperature_c, self.vibration_mm_s if self._over(v, self.fail_vibration) or self._over(t, self.fail_temp_c): return "fail" if self._over(v, self.warn_vibration) or self._over(t, self.warn_temp_c): return "warn" return "ok"
@classmethod def from_csv_row(cls, row: dict[str, str]) -> Self: def number(text: str) -> float | None: return float(text) if text else None
return cls( row["sensor_id"], number(row["temperature_c"]), number(row["vibration_mm_s"]), row["status"], )
r = SensorReading("S4", 24.1, 4.54, "warn")print(r.computed_status(), r.status)warn warnThe thresholds are the same for every reading, so they are class attributes (marked). The four values of one row are instance attributes. The two numbers can be None, because the file has blank cells. _over is a static method, because it needs neither the reading nor the class. Its single underscore marks it as an internal helper, not part of the interface. It returns False for a missing value, so a blank cell never triggers an alert. from_csv_row is the alternative constructor that parses one row of text.
Step 2 — Build one object per row
Section titled “Step 2 — Build one object per row”with open("data/sensors.csv", newline="", encoding="utf-8") as f: readings = [SensorReading.from_csv_row(row) for row in csv.DictReader(f)]
print(len(readings), readings[103].sensor_id, readings[103].vibration_mm_s)print(Counter(r.computed_status() for r in readings))8064 S4 4.54Counter({'ok': 7588, 'warn': 452, 'fail': 24})The class method turns each text row into an object with real numbers or None. The counts are close to the file’s own counts: ok 7,587, warn 453 and fail 24 (see the data dictionary).
Step 3 — Compare with the file
Section titled “Step 3 — Compare with the file”disagree = [r for r in readings if r.computed_status() != r.status]print(len(disagree))for r in disagree: print(r.sensor_id, r.temperature_c, r.vibration_mm_s, r.status, r.computed_status())1S4 24.55 None warn okThe rule agrees with the file on 8,063 of 8,064 rows. The one difference is a blank vibration cell. The sensor set its status from the real vibration, which was high enough for warn; only the logged value was lost. The object model made this check short, because each row knows how to compute its own status.
Common mistakes:
- Putting the thresholds in
__init__as instance attributes. Every object then carries 4 copies of the same numbers, and changing the rule means changing every object. - Treating
Noneas 0 or comparing it with>=.None >= 4.5raises aTypeError. Testis not Nonefirst. - Calling
SensorReading(row)with the raw dict.__init__expects clean values; the class method is the place that parses text.
Example 2 — Customer records with shared churn rules
Section titled “Example 2 — Customer records with shared churn rules”Goal: Turn the rows of data/customers.csv into Customer objects with read-only risk flags, then check that the flags really separate churners from loyal customers.
Step 1 — Write the class with properties
Section titled “Step 1 — Write the class with properties”import csvfrom typing import Self
class Customer: # Churn rules (module 01): shared by every customer. short_tenure_months = 6 low_logins = 3
def __init__( self, customer_id: str, tenure_months: int, logins_last_30d: int, contract: str, churned: bool, ): self.customer_id = customer_id self.tenure_months = tenure_months self.logins_last_30d = logins_last_30d self.contract = contract self.churned = churned
@classmethod def from_csv_row(cls, row: dict[str, str]) -> Self: return cls( row["customer_id"], int(row["tenure_months"]), int(row["logins_last_30d"]), row["contract"], row["churned"] == "1", )
@property def is_new(self) -> bool: return self.tenure_months <= self.short_tenure_months
@property def is_inactive(self) -> bool: return self.logins_last_30d <= self.low_logins
@property def risk_flags(self) -> int: """Number of churn warning signs: 0 to 3.""" monthly = self.contract == "month-to-month" return self.is_new + self.is_inactive + monthly # True counts as 1is_new and is_inactive are properties without setters, so they are read-only and always agree with the stored data. risk_flags adds three bool values; True counts as 1 (module 01).
Step 2 — Load the customers and inspect one
Section titled “Step 2 — Load the customers and inspect one”with open("data/customers.csv", newline="", encoding="utf-8") as f: customers = [Customer.from_csv_row(row) for row in csv.DictReader(f)]
c = next(c for c in customers if c.customer_id == "C03991")print(len(customers), c.customer_id, c.tenure_months, c.logins_last_30d, c.contract)print(c.is_new, c.is_inactive, c.risk_flags, c.churned)5000 C03991 6 2 month-to-monthTrue True 3 TrueCustomer C03991 has all three warning signs, and did churn. One customer proves nothing, so the next step checks all 5,000.
Step 3 — Churn rate by number of flags
Section titled “Step 3 — Churn rate by number of flags”def churn_by_flags(customers: list[Customer]) -> None: for flags in range(4): group = [c for c in customers if c.risk_flags == flags] rate = sum(c.churned for c in group) / len(group) print(f"{flags} flags: {len(group):>5} customers, churn {rate:6.1%}")
churn_by_flags(customers)0 flags: 1948 customers, churn 4.9%1 flags: 1897 customers, churn 16.7%2 flags: 1073 customers, churn 45.8%3 flags: 82 customers, churn 73.2%Churn rises with every flag, from 4.9% to 73.2%. The rule is a useful baseline model. The function works with the objects through their public names only.
Step 4 — Change a shared rule for every customer
Section titled “Step 4 — Change a shared rule for every customer”Customer.low_logins = 5 # what if "inactive" meant 5 logins or fewer?print(c.is_inactive, sum(c.is_inactive for c in customers))Customer.low_logins = 3 # restore the ruleprint(sum(c.is_inactive for c in customers))True 980395One assignment to the class attribute changed the rule for all 5,000 objects at once, because none of them has its own low_logins. This is a quick way to run a what-if analysis on a rule.
Common mistakes:
- Writing
c.low_logins = 5to change the rule. It creates an instance attribute on one customer only, and the other 4,999 keep the old rule. - Storing
is_newas an attribute in__init__. Iftenure_monthschanges later, the stored flag is wrong. A property is computed on every read. - Reading
row["churned"]as aboolwithbool("0"). The string"0"is truthy (module 01). Compare the text:row["churned"] == "1".
Example 3 — Fix a training history that leaks between runs
Section titled “Example 3 — Fix a training history that leaks between runs”Goal: A small training class fits the line price ≈ w × sqft with gradient descent (module 03) and records the loss of each epoch. Two runs with different learning rates show each other’s losses. Find and fix the bug.
Step 1 — Run the buggy class
Section titled “Step 1 — Run the buggy class”from typing import Self
class TrainingRun: history = [] # loss per epoch
def __init__(self, learning_rate: float): self.learning_rate = learning_rate self.w = 0.0
def fit(self, x: list[float], y: list[float], epochs: int) -> Self: n = len(x) for _ in range(epochs): errors = [self.w * xi - yi for xi, yi in zip(x, y)] mse = sum(e * e for e in errors) / n gradient = 2 * sum(e * xi for e, xi in zip(errors, x)) / n self.w -= self.learning_rate * gradient self.history.append(round(mse, 4)) return self
# sqft and price of 4 houses, in thousands, from data/houses.csvx = [2.42, 1.61, 1.26, 1.79]y = [1097.5, 486.5, 223.0, 431.0]slow = TrainingRun(learning_rate=0.01).fit(x, y, epochs=3)fast = TrainingRun(learning_rate=0.1).fit(x, y, epochs=3)print(len(slow.history), len(fast.history))6 6Each run trained for 3 epochs, but each history has 6 entries. Something is shared.
Step 2 — Find where the list lives
Section titled “Step 2 — Find where the list lives”print(vars(slow))print("history" in vars(TrainingRun), slow.history is fast.history){'learning_rate': 0.01, 'w': 63.013390093299925}True Truevars(slow) has learning_rate and w, but no history. The list lives in the class namespace, and both runs append to it. self.w -= ... is an assignment, so each run got its own w. self.history.append(...) is not an assignment, so it used the shared list.
Step 3 — Create the list in init
Section titled “Step 3 — Create the list in init”class TrainingRun: def __init__(self, learning_rate: float): self.learning_rate = learning_rate self.w = 0.0 self.history: list[float] = [] # one list per run
def fit(self, x: list[float], y: list[float], epochs: int) -> Self: n = len(x) for _ in range(epochs): errors = [self.w * xi - yi for xi, yi in zip(x, y)] mse = sum(e * e for e in errors) / n gradient = 2 * sum(e * xi for e, xi in zip(errors, x)) / n self.w -= self.learning_rate * gradient self.history.append(round(mse, 4)) return self
slow = TrainingRun(learning_rate=0.01).fit(x, y, epochs=3)fast = TrainingRun(learning_rate=0.1).fit(x, y, epochs=3)print(slow.history)print(fast.history)[419169.625, 370401.0655, 327875.8291][419169.625, 81741.3559, 43194.4817]Each run now has its own history. Both start from the same loss, because w starts at 0. The larger learning rate lowers the loss faster.
Step 4 — Compare the runs
Section titled “Step 4 — Compare the runs”for run in (slow, fast): print(f"lr={run.learning_rate}: w={run.w:.1f}, final MSE={run.history[-1]:,.0f}")lr=0.01: w=63.0, final MSE=327,876lr=0.1: w=326.1, final MSE=43,194w is the price in thousands of USD per 1,000 sqft. After 3 epochs, the faster run is much closer to a good fit. With the bug, this comparison was impossible, because both histories mixed both runs.
Common mistakes:
- Thinking that
self.history.append(...)creates an instance attribute. Only an assignment (self.history = ...) does that. - Fixing the bug with
history = Noneat class level andif self.history is Nonechecks everywhere. Create the list in__init__; it is simpler. - Trusting a quick test with one instance. The bug appears only with two or more instances, so test with two.
Example 4 — Load a dataset with Dataset.from_csv
Section titled “Example 4 — Load a dataset with Dataset.from_csv”Goal: Start minilearn’s Dataset class: it holds the features X (a list of rows) and the target y of a supervised learning problem. Build it from data/houses.csv with an alternative constructor.
In supervised learning, a model learns from examples whose answers are known, then predicts the answer for new examples. A feature is an input column that the model uses, such as sqft. The target is the column that the model predicts, such as price. minilearn follows scikit-learn: X is a table with one row per sample, and y has one value per sample.
Step 1 — Write the initializer with checks
Section titled “Step 1 — Write the initializer with checks”class Dataset: """Features X (one row per sample) and target y for a learning problem."""
def __init__(self, X: list[list[float]], y: list[float], feature_names: list[str]): if len(X) != len(y): raise ValueError(f"X has {len(X)} rows but y has {len(y)} values") if any(len(row) != len(feature_names) for row in X): raise ValueError(f"every row of X needs {len(feature_names)} values") self.X = X self.y = y self.feature_names = feature_names
toy = Dataset([[1.0, 2.0], [3.0, 4.0]], [10.0, 20.0], ["a", "b"])print(toy.X, toy.y, toy.feature_names)[[1.0, 2.0], [3.0, 4.0]] [10.0, 20.0] ['a', 'b']The initializer checks the shapes once, so every Dataset object is valid. X breaks the snake_case rule on purpose: scikit-learn and the math of ML write the feature matrix as a capital X. ruff accepts it with the course settings.
Step 2 — Add read-only properties
Section titled “Step 2 — Add read-only properties”class Dataset: """Features X (one row per sample) and target y for a learning problem."""
def __init__(self, X: list[list[float]], y: list[float], feature_names: list[str]): if len(X) != len(y): raise ValueError(f"X has {len(X)} rows but y has {len(y)} values") if any(len(row) != len(feature_names) for row in X): raise ValueError(f"every row of X needs {len(feature_names)} values") self.X = X self.y = y self.feature_names = feature_names
@property def n_samples(self) -> int: return len(self.X)
@property def n_features(self) -> int: return len(self.feature_names)
toy = Dataset([[1.0, 2.0], [3.0, 4.0]], [10.0, 20.0], ["a", "b"])print(toy.n_samples, toy.n_features)2 2The class grows in place: the new lines are marked. The counts are computed from X and feature_names, so they never go out of date. scikit-learn uses the same names: n_samples and n_features.
Step 3 — Add the alternative constructor
Section titled “Step 3 — Add the alternative constructor”import csvfrom typing import Self
class Dataset: """Features X (one row per sample) and target y for a learning problem."""
def __init__(self, X: list[list[float]], y: list[float], feature_names: list[str]): if len(X) != len(y): raise ValueError(f"X has {len(X)} rows but y has {len(y)} values") if any(len(row) != len(feature_names) for row in X): raise ValueError(f"every row of X needs {len(feature_names)} values") self.X = X self.y = y self.feature_names = feature_names
@property def n_samples(self) -> int: return len(self.X)
@property def n_features(self) -> int: return len(self.feature_names)
@staticmethod def _to_float(text: str, column: str, line: int) -> float: if not text.strip(): raise ValueError(f"line {line}: blank value in column {column!r}") return float(text)
@classmethod def from_csv(cls, path: str, target: str, features: list[str]) -> Self: X: list[list[float]] = [] y: list[float] = [] with open(path, newline="", encoding="utf-8") as f: # line 1 is the header, so the first data row is line 2 for line, row in enumerate(csv.DictReader(f), start=2): X.append([cls._to_float(row[name], name, line) for name in features]) y.append(cls._to_float(row[target], target, line)) return cls(X, y, features)
houses = Dataset.from_csv("data/houses.csv", target="price", features=["sqft"])print(houses.n_samples, houses.n_features, houses.feature_names)print(houses.X[:3], houses.y[:3])3000 1 ['sqft'][[2420.0], [1610.0], [1260.0]] [1097500.0, 486500.0, 223000.0]from_csv does the file work and then calls cls(X, y, features). So the shape checks of __init__ run for CSV data too. The static method _to_float is an internal helper with a clear error message. All the methods now live in one class namespace: vars(Dataset) holds __init__, n_samples, n_features, _to_float and from_csv.
Step 4 — Load two features and meet a blank cell
Section titled “Step 4 — Load two features and meet a blank cell”two = Dataset.from_csv("data/houses.csv", target="price", features=["sqft", "bedrooms"])print(two.n_samples, two.n_features, two.X[0])3000 2 [2420.0, 4.0]Dataset.from_csv("data/houses.csv", target="price", features=["sqft", "school_rating"])ValueError: line 22: blank value in column 'school_rating'school_rating has 90 blank cells. The first one is on line 22 of the file (house H0021). The error names the line and the column, so you can find the problem at once. The mini-project adds an option to skip such rows.
Common mistakes:
- Writing
return Dataset(X, y, features)in the class method. It works today, but a subclass ofDatasetwould get a plainDatasetback. Usecls(...). - Parsing the file inside
__init__. Then you cannot build aDatasetfrom lists in a test. Keep__init__for clean values and add one class method per source. - Making
n_samplesa stored attribute. It can disagree withXafter a change; a property cannot.
Example 5 — Validate settings with properties
Section titled “Example 5 — Validate settings with properties”Goal: A monitoring dashboard lets an engineer set alert rules on data/sensors.csv, such as “vibration at or above 4.5 mm/s”. Give the AlertRule class two validated settings, so that a bad value fails at the line that sets it. Then compare with the way scikit-learn validates a model.
Step 1 — Write the class with two properties
Section titled “Step 1 — Write the class with two properties”class AlertRule: """An alert on one numeric column of data/sensors.csv."""
_valid_columns = ("temperature_c", "vibration_mm_s") # the alert columns
def __init__(self, column: str, threshold: float): self.column = column # runs the column setter self.threshold = threshold # runs the threshold setter
@property def column(self) -> str: return self._column
@column.setter def column(self, value: str) -> None: if value not in self._valid_columns: allowed = self._valid_columns raise ValueError(f"column must be one of {allowed}, got {value!r}") self._column = value
@property def threshold(self) -> float: return self._threshold
@threshold.setter def threshold(self, value: float) -> None: if isinstance(value, bool) or not isinstance(value, (int, float)): raise TypeError(f"threshold must be a number, got {type(value).__name__}") if value <= 0: raise ValueError(f"threshold must be > 0, got {value}") self._threshold = value
def matches(self, row: dict[str, str]) -> bool: text = row[self.column] return bool(text) and float(text) >= self.threshold
rule = AlertRule("vibration_mm_s", 4.5)print(rule.column, rule.threshold, vars(rule))print(rule.matches({"vibration_mm_s": "4.54"}), rule.matches({"vibration_mm_s": ""}))vibration_mm_s 4.5 {'_column': 'vibration_mm_s', '_threshold': 4.5}True FalseThe public names are column and threshold. The stored values have one underscore, because callers should go through the properties. The allowed columns are a class attribute, the same for every rule. matches returns False for a blank cell.
Step 2 — Try bad values
Section titled “Step 2 — Try bad values”bad_values = [ {"column": "vibration", "threshold": 4.5}, {"column": "vibration_mm_s", "threshold": 0}, {"column": "vibration_mm_s", "threshold": "4.5"}, {"column": "vibration_mm_s", "threshold": True},]for kwargs in bad_values: try: AlertRule(**kwargs) except (TypeError, ValueError) as exc: print(f"{type(exc).__name__}: {exc}")ValueError: column must be one of ('temperature_c', 'vibration_mm_s'), got 'vibration'ValueError: threshold must be > 0, got 0TypeError: threshold must be a number, got strTypeError: threshold must be a number, got bool**kwargs unpacks each dict into keyword arguments (module 05). A wrong type raises TypeError, and a value of the right type outside the allowed range raises ValueError. This is the convention of the standard library.
Step 3 — Change a setting and apply the rule
Section titled “Step 3 — Change a setting and apply the rule”import csv
with open("data/sensors.csv", newline="", encoding="utf-8") as f: s4_rows = [row for row in csv.DictReader(f) if row["sensor_id"] == "S4"]
for threshold in (4.5, 6.0, -1.0): try: rule.threshold = threshold except ValueError as exc: print("rejected:", exc) print(rule.threshold, sum(rule.matches(row) for row in s4_rows))4.5 4116.0 278rejected: threshold must be > 0, got -1.06.0 278The setter checks every assignment, not only the first. After the rejected value, the rule keeps its old, valid setting, so the last count repeats the 6.0 result. A dashboard slider that sets rule.threshold cannot break the rule.
Step 4 — See how scikit-learn validates a model
Section titled “Step 4 — See how scikit-learn validates a model”from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=0) # accepted: no check yetprint(knn.n_neighbors, knn.get_params()["n_neighbors"])try: knn.fit([[0.0], [1.0]], [0, 1])except ValueError as exc: print(type(exc).__name__) print(str(exc).split(". ")[0])0 0InvalidParameterErrorThe 'n_neighbors' parameter of KNeighborsClassifier must be an int in the range [1, inf) or NoneA model is a different kind of object. scikit-learn’s estimators store each constructor argument unchanged, under the same name, and validate all of them when fit() starts. The error type is a subclass of ValueError. minilearn’s estimators follow the same rule, because module 19 builds get_params() and set_params() on it. So: validating properties for settings, records and configs such as AlertRule; checks in fit() for models.
Common mistakes:
- Storing the value as
self.thresholdinside the setter. The setter calls itself untilRecursionError: maximum recursion depth exceeded. Store it underself._threshold. - Giving the getter and the setter different names.
@threshold.settermust decorate a method that is also namedthreshold. - Checking
isinstance(value, (int, float))alone. It acceptsTrueandFalse, becauseboolis a subclass ofint.
Example 6 — Refactor procedural min-max scaling into a class
Section titled “Example 6 — Refactor procedural min-max scaling into a class”Goal: Min-max scaling (module 05) maps each value to (x - min) / (max - min), so the training data spans 0 to 1. Turn a procedural version into a MinMaxScaler class with the scikit-learn interface: fit, transform and learned attributes that end in _.
Step 1 — Look at the procedural version
Section titled “Step 1 — Look at the procedural version”def fit_min_max(values: list[float]) -> dict[str, float]: return {"min": min(values), "max": max(values)}
def transform_min_max(values: list[float], params: dict[str, float]) -> list[float]: span = params["max"] - params["min"] return [round((v - params["min"]) / span, 3) for v in values]
train = [19.5, 20.7, 20.1, 21.2, 21.2, 20.8] # data/readings.txt, lines 37-42params = fit_min_max(train)print(params, transform_min_max(train, params)){'min': 19.5, 'max': 21.2} [0.0, 0.706, 0.353, 1.0, 1.0, 0.765]It works, but the caller must carry the params dict from one function to the next and must know its keys. Nothing stops a caller from passing the parameters of another column.
Step 2 — Move the state and the functions into a class
Section titled “Step 2 — Move the state and the functions into a class”from typing import Self
class NotFittedError(ValueError): """Raised when a model is used before fit()."""
class MinMaxScaler: def fit(self, values: list[float]) -> Self: self.data_min_ = min(values) # learned attributes end with _ self.data_max_ = max(values) return self
def transform(self, values: list[float]) -> list[float]: self._check_fitted() span = self.data_max_ - self.data_min_ return [round((v - self.data_min_) / span, 3) for v in values]
def _check_fitted(self) -> None: if not hasattr(self, "data_min_"): raise NotFittedError("MinMaxScaler is not fitted yet; call fit() first")
scaler = MinMaxScaler().fit(train)print(scaler.data_min_, scaler.data_max_, scaler.transform(train))19.5 21.2 [0.0, 0.706, 0.353, 1.0, 1.0, 0.765]The object carries its own parameters, so transform cannot get the wrong ones. fit returns self, so MinMaxScaler().fit(train) gives back the fitted scaler. hasattr(obj, name) returns True when the attribute exists; the learned attributes exist only after fit. NotFittedError is a custom exception (module 06); minilearn uses it from now on.
Step 3 — Scale new data with the training parameters
Section titled “Step 3 — Scale new data with the training parameters”new_readings = [19.3, 21.0, 22.9] # later readings from the same sensorprint(scaler.transform(new_readings))[-0.118, 0.882, 2.0]New data uses the minimum and maximum learned from the training data, so values outside the training range land below 0 or above 1. This is correct. Refitting on the new data would leak information from the test set into the preprocessing, a mistake called data leakage (module 33 covers it in depth).
Step 4 — Use the scaler before fit
Section titled “Step 4 — Use the scaler before fit”try: MinMaxScaler().transform(train)except NotFittedError as exc: print(type(exc).__name__, "-", exc)NotFittedError - MinMaxScaler is not fitted yet; call fit() firstThe error message says what to do. Without _check_fitted, the caller would see AttributeError: 'MinMaxScaler' object has no attribute 'data_min_', which is less clear.
Common mistakes:
- Calling
fiton the test data. Fit once on the training data, thentransformboth sets. - Setting
self.data_min_ = Nonein__init__“to be safe”. Thenhasattris alwaysTrue, and the fitted check must test forNoneinstead. scikit-learn creates learned attributes only infit. - Forgetting
return selfinfit. ThenMinMaxScaler().fit(train)returnsNone, and the next.transform(...)raisesAttributeError: 'NoneType' object has no attribute 'transform'.
Example 7 — Keep running statistics safe behind properties
Section titled “Example 7 — Keep running statistics safe behind properties”Goal: A monitoring service receives one temperature at a time and must report the mean and the variance at any moment, without storing every value. Build a RunningStats class whose internal state cannot be changed by mistake.
Welford’s algorithm updates the count, the mean and a running sum of squared differences (m2) with each new value. The population variance is then m2 / count. You do not need to memorize the update; the point is that three numbers must stay consistent with each other.
Step 1 — Write the class with internal state
Section titled “Step 1 — Write the class with internal state”class RunningStats: """Mean and population variance of a stream of numbers (Welford's algorithm)."""
def __init__(self): self._count = 0 self._mean = 0.0 self._m2 = 0.0 # sum of squared differences from the mean
def update(self, value: float) -> None: self._count += 1 delta = value - self._mean self._mean += delta / self._count self._m2 += delta * (value - self._mean)
@property def count(self) -> int: return self._count
@property def mean(self) -> float: return self._mean
@property def variance(self) -> float: return self._m2 / self._count if self._count else 0.0The three numbers are internal (_count, _mean, _m2). The interface is update() plus three read-only properties. Callers cannot set mean by accident.
Step 2 — Stream the readings file through it
Section titled “Step 2 — Stream the readings file through it”stats = RunningStats()with open("data/readings.txt", encoding="utf-8") as f: for line in f: try: stats.update(float(line)) except ValueError: continue # skip "error", the empty line and "n/a"
print(stats.count, round(stats.mean, 4), round(stats.variance, 4))40 21.0625 1.1453The object read 43 lines, skipped the 3 broken ones and kept only three numbers in memory. The same code works for a file of a billion lines.
Step 3 — Check against the statistics module
Section titled “Step 3 — Check against the statistics module”import mathimport statistics
valid = []with open("data/readings.txt", encoding="utf-8") as f: for line in f: try: valid.append(float(line)) except ValueError: continueprint(math.isclose(stats.mean, statistics.fmean(valid)))print(math.isclose(stats.variance, statistics.pvariance(valid)))TrueTruestatistics.fmean and statistics.pvariance (module 09) need the whole list. The running version gives the same answers from one pass. Compare floats with math.isclose(), as in module 01.
Step 4 — Try to break the state
Section titled “Step 4 — Try to break the state”try: stats.mean = 0.0except AttributeError as exc: print("blocked:", exc)stats._mean = 0.0 # possible, but the underscore said "internal"print(round(stats.mean, 4), round(stats.variance, 4))blocked: property 'mean' of 'RunningStats' object has no setter0.0 1.1453The read-only property stops the honest mistake. The underscore does not stop a determined caller: stats._mean = 0.0 works and leaves the object inconsistent (the mean is now 0 but the variance is not). Python trusts the caller to respect _ names. This is the meaning of the phrase “we are all consenting adults here” in the Python community.
Common mistakes:
- Making
meana plain public attribute. One straystats.mean = ...silently corrupts every later update. - Using
__meanfor privacy. It only renames the attribute to_RunningStats__mean; it adds no protection that matters, and it makes debugging harder. - Dividing by
self._countwith no values. Theif self._count else 0.0guard avoids aZeroDivisionErroron an empty stream.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
Forgetting self in a method definition |
TypeError: ...takes 0 positional arguments but 1 was given |
Make self the first parameter |
Forgetting self. inside a method: temperature_c * 2 |
NameError: name 'temperature_c' is not defined |
Read attributes through self.temperature_c |
| A list or dict as a class attribute | Every instance sees the others’ data | Create it in __init__: self.runs = [] |
self.count += 1 for a class-wide counter |
The class counter stays at 0 | Write ClassName.count += 1 |
obj.limit = 5 to change a shared setting |
Only that one object changes | Assign through the class: Cls.limit = 5 |
self.n = value inside the setter of property n |
RecursionError: maximum recursion depth exceeded |
Store under another name: self._n = value |
| Getter and setter with different names | The setter is never used, or AttributeError: ... has no setter |
Name both methods like the property |
| Assigning to a property without a setter | AttributeError: property 'x' of 'C' object has no setter |
Add a setter, or treat it as read-only |
isinstance(value, int) to validate a count |
True and False are accepted |
Also reject bool: isinstance(value, bool) |
A class method that returns ClassName(...) |
Subclasses get instances of the base class | Return cls(...) |
Forgetting @classmethod on from_csv |
TypeError: ... missing 1 required positional argument |
Add the decorator; name the first parameter cls |
A return annotation that names the class being defined, such as -> Dataset |
NameError: name 'Dataset' is not defined when the class is defined |
Use typing.Self, or quote it: -> "Dataset" |
obj.__secret outside the class |
AttributeError: 'C' object has no attribute '__secret' |
Use a public name or a property; __x is renamed _C__x |
print(obj) in a report |
<__main__.C object at 0x...>, different on every run |
Print attributes, or add __repr__ (module 20) |
Learned attributes set in __init__ |
hasattr(model, "coef_") is True before fit |
Create name_ attributes only in fit |
fit without return self |
AttributeError: 'NoneType' object has no attribute 'transform' |
End fit with return self |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: frameworks turn each HTTP request into an object (
request.method,request.headers), and FastAPI uses pydantic classes to validate request bodies. Django models map each class to a database table and each class attribute to a column. - Games and simulations: each character is an instance with its own position and health; shared settings such as gravity are class attributes;
player.move()andenemy.take_damage(10)are methods. - Automation and tooling:
pathlib.Path,logging.Logger,datetimeandargparse.ArgumentParserare classes. Alternative constructors such asdatetime.fromisoformat()andPath.home()are class methods. - Libraries and APIs: a client object such as
httpx.Clientkeeps its settings (base URL, timeouts) as attributes and offers methods (get,post) that use them, like a model keeps its hyperparameters.
Summary
Section titled “Summary”- A class is a blueprint; an instance is one object made from it. Attributes hold the state; methods are the behavior.
__init__sets the starting attributes of a new instance. Create instance attributes there withself.name = value.selfis the instance before the dot.obj.method()runsCls.method(obj).- Python looks up
obj.namein the instance namespace (vars(obj)) first, then in the class namespace. - Class attributes are shared. Use them for constants and defaults. Never use a mutable class attribute for per-instance data; create it in
__init__. - Assigning through an instance creates an instance attribute that shadows the class attribute. Change a shared value through the class.
@classmethodreceives the class ascls; use it for alternative constructors such asDataset.from_csv(), and returncls(...)with the hintSelf.@staticmethodreceives nothing extra; use it for helpers that belong to the class topic.@propertygives computed, read-only attributes; add a setter to validate every assignment. Store the value under_name._namemeans internal.__nameis renamed to_ClassName__nameto avoid clashes in subclasses; it is not privacy.name_marks a learned attribute in scikit-learn style.
Self-check questions
Section titled “Self-check questions”Q1. What is the difference between a class and an instance? Give a data example.
Answer
A class is the blueprint: it defines which attributes and methods objects have. An instance is one object made from the class, with its own attribute values. SensorReading is a class; the reading of sensor S4 at 00:00 on 2024-05-01 is one instance of it.
Q2. r = SensorReading("S1", 20.21, 2.5). What does Python do, step by step?
Answer
Python creates a new, empty SensorReading object. It calls SensorReading.__init__ with the new object as self and the three arguments. __init__ stores the attributes on self. The call returns the object, and r refers to it.
Q3. Why does def to_fahrenheit(): inside a class fail with “takes 0 positional arguments but 1 was given” when you call r.to_fahrenheit()?
Answer
r.to_fahrenheit() runs SensorReading.to_fahrenheit(r). Python passes the instance as the first argument. The method has no parameter to receive it. Add self as the first parameter.
Q4. A class has unit = "°C" in its body. You run a.unit = "°F" on one instance a. What do a.unit, b.unit (another instance) and vars(a) show?
Answer
a.unit is "°F", from the new instance attribute. b.unit is still "°C", from the class. vars(a) now contains 'unit': '°F' next to the other instance attributes. The assignment shadowed the class attribute for a only.
Q5. Why is history = [] in a class body a bug when each instance should have its own history? How do you fix it?
Answer
The list is created once, when the class is defined, and lives in the class namespace. self.history.append(x) finds that one shared list, because an append is not an assignment. Every instance writes into it. Create the list in __init__: self.history = [].
Q6. When do you use a class method instead of __init__? Why should it end with return cls(...)?
Answer
Use a class method as an alternative constructor, when the input comes in another shape: a CSV row, a file path, a dict. It parses the input and then calls cls(...), so every object still goes through __init__ and its checks. cls is the class that the method was called on, so a subclass gets an instance of itself.
Q7. A helper turns "2.5" into 2.5 and "" into None. Should it be an instance method, a class method, a static method or a module function?
Answer
It needs neither the instance nor the class, so not an instance or class method. If only the class uses it, as an internal parsing step, a static method such as _parse_float is fine. If other code needs it too, make it a module-level function.
Q8. What is wrong with this setter, and what happens when it runs?
@n_neighbors.setterdef n_neighbors(self, value): if value < 1: raise ValueError("n_neighbors must be >= 1") self.n_neighbors = valueAnswer
self.n_neighbors = value assigns to the property again, so the setter calls itself. It never ends until Python raises RecursionError. Store the value under another name: self._n_neighbors = value, and return it from the getter.
Q9. Why is n_samples a property of Dataset and not an attribute set in __init__?
Answer
A property is computed from X on every read, so it is always correct. A stored count would be wrong after a change to X. It is also read-only, so no caller can set a count that contradicts the data.
Q10. Inside class Splitter, __init__ sets self.__seed = 42. What does vars(Splitter(42)) show? Is the seed private?
Answer
{'_Splitter__seed': 42}. Name mangling rewrote __seed to _Splitter__seed. It is not private: any code can read obj._Splitter__seed. Mangling exists to stop a subclass from overwriting the attribute by accident.
Q11. What do the trailing underscores in mean_, scale_ and coef_ mean in scikit-learn and minilearn?
Answer
They mark learned attributes: values that fit() computes from the data. They do not exist before fit, so hasattr(model, "coef_") tells you if a model is fitted. Constructor arguments such as n_neighbors have no trailing underscore.
Q12. Model.created is a class attribute that counts instances. Why does self.created += 1 in __init__ fail to count?
Answer
self.created += 1 means self.created = self.created + 1. The right side reads the class value (0). The assignment then creates an instance attribute created = 1 on the new object. The class attribute stays at 0. Write Model.created += 1.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 25 exercises on classes, attributes, methods, properties and encapsulation, with hints and full solutions.
- Mini-project: start
minilearnwithDataset.from_csv, aStandardScaler, a one-featureLinearRegressionand the MSE and R² metrics. - Cheat sheet: class syntax, the three kinds of methods, properties and naming conventions on one page.
- Next module: 19. Inheritance and polymorphism builds
BaseEstimatorand mixins withsuper(), and adds aKNNClassifierthat validates its settings infit()and predicts.