18. Classes and objects — Cheat sheet
The essentials of module 18 on one page. Every runnable block on this page is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| define a class | class Name: with a CapWords name |
class SensorReading: |
| set the starting state of each object | def __init__(self, ...): |
self.sensor_id = sensor_id |
| create an instance | call the class | r = SensorReading("S1", 20.21) |
| read or change an attribute | obj.name |
r.temperature_c = 21.0 |
| see what an instance stores | vars(obj) (same as obj.__dict__) |
{'sensor_id': 'S1', ...} |
| see what a class stores | vars(Cls) |
methods, class attributes, properties |
| check the class of an object | type(obj), isinstance(obj, Cls) |
isinstance(r, SensorReading) |
| share one value across all instances | a class attribute in the class body | warn_vibration = 4.5 |
| change a shared value for everyone | assign through the class | Reading.warn_vibration = 5.0 |
| give each instance its own list or dict | create it in __init__ |
self.history = [] |
| count instances | a class attribute changed through the class | Model.created += 1 |
| build objects from a file, row or dict | @classmethod alternative constructor |
Dataset.from_csv(path, ...) |
| a helper that needs no instance or class | @staticmethod (or a module function) |
SensorReading._parse_float("2.5") |
| a computed, read-only attribute | @property |
dataset.n_samples |
| validate every assignment of a setting | @property plus @name.setter |
settings.n_neighbors = 0 raises ValueError |
| compute an expensive value once | @functools.cached_property |
report.summary |
| mark a name as internal | one leading underscore | self._n_neighbors, _check_fitted() |
| avoid a name clash with subclasses | two leading underscores (name mangling) | self.__calls → _Counter__calls |
| mark a learned model attribute | trailing underscore, set in fit |
self.coef_, self.mean_ |
allow chaining after fit |
return self |
Scaler().fit(X).transform(X) |
| check if a model is fitted | hasattr(model, "coef_") |
False before fit |
| hint the type “instance of this class” | typing.Self |
def from_csv(cls, ...) -> Self: |
| hint a class attribute | typing.ClassVar |
created: ClassVar[int] = 0 |
Class anatomy
Section titled “Class anatomy”from typing import ClassVar, Self
class SensorReading: """One reading from data/sensors.csv.""" # class docstring
unit: ClassVar[str] = "°C" # class attribute: shared created: ClassVar[int] = 0 # class-wide counter
def __init__(self, sensor_id: str, temperature_c: float): # initializer self.sensor_id = sensor_id # instance attributes: one set per object self.temperature_c = temperature_c SensorReading.created += 1 # change the counter through the class
def to_fahrenheit(self) -> float: # instance method: works on self return round(self.temperature_c * 9 / 5 + 32, 2)
@classmethod def from_line(cls, line: str) -> Self: # class method: alternative constructor sensor_id, temp = line.strip().split(",") return cls(sensor_id, float(temp)) # cls(...), not SensorReading(...)
@staticmethod def is_plausible(temperature_c: float) -> bool: # static method: no self, no cls return -40.0 <= temperature_c <= 85.0
@property def label(self) -> str: # property: computed on every read return f"{self.sensor_id}: {self.temperature_c}{self.unit}"
r = SensorReading.from_line("S4,24.52\n")print(r.label, r.to_fahrenheit(), r.is_plausible(99.0), SensorReading.created)S4: 24.52°C 76.14 False 1| Piece | Syntax | Notes |
|---|---|---|
| class statement | class Name: |
creates a class object bound to Name |
| initializer | def __init__(self, ...) |
runs after Python creates the object; must return None |
| instance attribute | self.x = value |
usually created in __init__ |
| class attribute | x = value in the class body |
one value in vars(Cls) |
| instance method | def m(self, ...) |
obj.m(a) runs Cls.m(obj, a) |
| class method | @classmethod def m(cls, ...) |
receives the class; works through subclasses |
| static method | @staticmethod def m(...) |
receives nothing extra |
| property | @property def x(self) |
read with obj.x, no parentheses |
self and attribute lookup
Section titled “self and attribute lookup”class Reading: unit = "°C"
def __init__(self, temperature_c: float): self.temperature_c = temperature_c
def to_fahrenheit(self) -> float: return self.temperature_c * 9 / 5 + 32
r = Reading(20.0)print(r.to_fahrenheit() == Reading.to_fahrenheit(r)) # the same callprint(vars(r), "unit" in vars(r), "unit" in vars(Reading))print(type(r).__name__, r.__class__ is Reading)True{'temperature_c': 20.0} False TrueReading TrueReading obj.name searches, in order:
| Step | Where | Found when |
|---|---|---|
| 1 | a @property on the class |
the class defines a property with that name |
| 2 | the instance namespace, vars(obj) |
self.name = ... ran |
| 3 | the class namespace, vars(type(obj)), then the base classes (module 19) |
a method or class attribute |
| 4 | none | AttributeError: 'C' object has no attribute 'name' |
Assigning obj.name = value writes to vars(obj), unless the class has a property with that name; then the setter runs.
| Built-in | Does | Example |
|---|---|---|
vars(obj) |
the instance namespace (a dict) | vars(r) |
hasattr(obj, "name") |
True if lookup finds it |
hasattr(model, "coef_") |
getattr(obj, "name", default) |
lookup by a string name | getattr(cfg, "epochs", 10) |
setattr(obj, "name", value) |
assignment by a string name | setattr(model, param, value) |
delattr(obj, "name") / del obj.name |
remove an instance attribute | the class value shows again |
type(obj) |
the class of the object | type(r) is Reading |
isinstance(obj, Cls) |
instance of Cls or of a subclass |
isinstance(r, Reading) |
Instance attributes vs class attributes
Section titled “Instance attributes vs class attributes”class Monitor: warn_mm_s = 4.5 # shared default alerts_wrong = [] # BUG: one list for all monitors
def __init__(self, sensor_id: str): self.sensor_id = sensor_id self.alerts: list[str] = [] # right: one list per monitor
a, b = Monitor("S1"), Monitor("S4")b.warn_mm_s = 6.0 # instance attribute shadows the default for b onlya.alerts_wrong.append("x") # mutates the shared listprint(a.warn_mm_s, b.warn_mm_s, b.alerts_wrong, a.alerts is b.alerts)4.5 6.0 ['x'] False| Operation | Effect |
|---|---|
obj.x (read) |
instance value if any, else the class value |
obj.x = v |
creates or replaces an instance attribute; shadows the class value |
Cls.x = v |
changes the class value for every instance without its own x |
obj.x.append(v) |
mutates the object that lookup found; with a class list, every instance sees it |
self.count += 1 |
reads the class value, writes an instance attribute: the class counter does not move |
Cls.count += 1 |
changes the class counter |
Three kinds of methods
Section titled “Three kinds of methods”| Instance method | Class method | Static method | |
|---|---|---|---|
| Decorator | none | @classmethod |
@staticmethod |
| First parameter | self |
cls |
none |
| Called as | obj.m() |
Cls.m() or obj.m() |
Cls.m() or obj.m() |
| Reads instance state | yes | no | no |
| Typical use | behavior of one object | alternative constructors, class-wide settings | helpers of the class topic |
Alternative constructors in the standard library and in pandas:
| Call | Builds |
|---|---|
dict.fromkeys(keys, value) |
a dict with one value for every key |
datetime.fromisoformat("2024-05-01T13:30:00") |
a datetime |
datetime.fromtimestamp(0, tz=UTC) |
a datetime from Unix time |
int.from_bytes(b"\x01\x00", "big") |
256 |
Path.home(), Path.cwd() |
a Path |
pd.DataFrame.from_records(rows), pd.DataFrame.from_dict(d) |
a DataFrame |
Properties
Section titled “Properties”from functools import cached_property
class RecommenderSettings: # a settings object, not a model estimator def __init__(self, n_neighbors: int = 5): self.n_neighbors = n_neighbors # runs the setter
@property def n_neighbors(self) -> int: # getter return self._n_neighbors # stored under another name
@n_neighbors.setter def n_neighbors(self, value: int) -> None: # setter: same name 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
class Report: def __init__(self, revenue: list[float]): self.revenue = revenue
@cached_property def total(self) -> float: # computed on the first read, then stored print("computing...") return round(sum(self.revenue), 2)
settings = RecommenderSettings(3)try: settings.n_neighbors = 0except ValueError as exc: print(exc, "| kept:", settings.n_neighbors)rep = Report([79.99, 249.0, 129.95])print(rep.total, rep.total, "total" in vars(rep))n_neighbors must be >= 1, got 0 | kept: 3computing...458.94 458.94 True| Pattern | Code | Use |
|---|---|---|
| read-only computed value | @property only |
n_samples, temperature_f |
| validated attribute | @property + @x.setter storing self._x |
settings, configs, records (not model estimators) |
| validate in the constructor too | self.x = x in __init__ |
the setter runs for new objects |
| delete hook | @x.deleter |
rare; clean-up on del obj.x |
| computed once, then stored | @functools.cached_property |
expensive summaries of data that does not change; del obj.x recomputes |
Naming and encapsulation
Section titled “Naming and encapsulation”| Name | Meaning | Enforced? |
|---|---|---|
name |
public interface | — |
_name |
internal; do not use from outside | no (convention; import * skips module-level _names) |
__name |
mangled to _ClassName__name inside the class body |
the rename only; not privacy |
__name__ |
Python’s special names (__init__, __repr__) |
never mangled; do not invent new ones |
name_ |
learned attribute set by fit (scikit-learn) |
no |
class_, type_ |
avoids a keyword or built-in name (PEP 8) | — |
CapWords |
class names: SensorReading, KNNClassifier |
PEP 8 |
class Base: def __init__(self): self.__calls = 0 # stored as _Base__calls
def tick(self) -> int: self.__calls += 1 return self.__calls
class Child(Base): def __init__(self): super().__init__() self.__calls = "child data" # stored as _Child__calls: no clash
c = Child()print(c.tick(), sorted(vars(c)), hasattr(c, "__calls"))1 ['_Base__calls', '_Child__calls'] FalseMangling rewrites identifiers inside the class body (also other.__x for any object), never strings: getattr(obj, "__x") is not rewritten.
The estimator pattern (scikit-learn and minilearn)
Section titled “The estimator pattern (scikit-learn and minilearn)”from typing import Self
class NotFittedError(ValueError): """Raised when a model is used before fit()."""
class MeanRegressor: def __init__(self, shift: float = 0.0): self.shift = shift # hyperparameter: stored unchanged
def fit(self, X: list[list[float]], y: list[float]) -> Self: if isinstance(self.shift, bool) or not isinstance(self.shift, (int, float)): raise TypeError("shift must be a number") # validate settings in fit self.mean_ = sum(y) / len(y) # learned attribute: ends with _, set only here return self # allows chaining
def predict(self, X: list[list[float]]) -> list[float]: if not hasattr(self, "mean_"): raise NotFittedError("MeanRegressor is not fitted yet; call fit() first") return [self.mean_ + self.shift for _ in X]
model = MeanRegressor()print(hasattr(model, "mean_"), model.fit([[1.0], [2.0]], [10.0, 20.0]).predict([[3.0]]))False [15.0]| Rule | Why |
|---|---|
__init__ stores each argument unchanged, under the same name |
get_params/set_params (module 19) read and write them by name |
fit validates the settings first |
a bad value set at any time fails at fit |
fit learns from data and returns self |
Model().fit(X, y).predict(X_new) |
learned attributes end with _ and exist only after fit |
hasattr is the fitted check |
| fit on the training set; transform train and test with the same object | no data leakage |
predict before fit raises a clear error |
not a confusing AttributeError |
Type hints for classes
Section titled “Type hints for classes”| Hint | Meaning |
|---|---|
def mean(readings: list[SensorReading]) -> float |
a class is a type |
-> Self (from typing) |
“an instance of the class this method runs on”; for alternative constructors and fit |
-> "Dataset" |
a quoted forward reference: one option to name the class inside its own body on Python 3.12 and 3.13 (others: Self, or from __future__ import annotations) |
x: ClassVar[int] = 0 |
a class attribute, not a per-instance field (matters for dataclasses, module 21) |
self.alerts: list[str] = [] |
annotate an instance attribute where you create it |
Common errors
Section titled “Common errors”| Error (last traceback line) | Typical cause | Fix |
|---|---|---|
TypeError: C.m() takes 0 positional arguments but 1 was given |
self missing in def m(): |
def m(self): |
NameError: name 'x' is not defined inside a method |
wrote x instead of self.x |
self.x |
TypeError: C.__init__() missing 1 required positional argument: 'y' |
an argument missing in C(...) |
pass it, or give a default |
AttributeError: 'C' object has no attribute 'x' |
typo, attribute never set, or a mangled __x read outside |
check vars(obj) |
AttributeError: property 'x' of 'C' object has no setter |
assigning a read-only property, or the setter has another name | add @x.setter with the same name |
RecursionError: maximum recursion depth exceeded |
the setter or getter of x uses self.x |
store self._x |
AttributeError: 'NoneType' object has no attribute 'predict' |
fit does not return self |
return self |
NameError: name 'C' is not defined at the def line |
-> C inside the body of class C |
-> Self or -> "C" |
Gotchas
Section titled “Gotchas”selfis not a keyword. It is the first parameter, and Python passes the instance to it. Forgetting it gives “takes 0 positional arguments but 1 was given”.- A mutable class attribute (
history = []) is shared by every instance. Create per-instance lists and dicts in__init__. - An immutable class attribute is safe:
obj.x = vcreates an instance attribute and leaves the class value alone. self.count += 1never changes a class counter. WriteCls.count += 1.obj.setting = vchanges one object.Cls.setting = vchanges every object that has no own value.- A property wins over the instance namespace. That is why
self.x = xin__init__runs the setter. - Inside a property, store the value under another name (
_x).self.xinside the getter or setter ofxrecurses forever. isinstance(True, int)isTrue. Rejectboolexplicitly when you validate counts.- Return
cls(...)from class methods, notClassName(...), so subclasses work. __xis not private: it becomes_ClassName__x. Use one underscore for internal names.print(obj)shows a memory address that changes on every run until you add__repr__(module 20).- Learned attributes such as
coef_belong infit, not in__init__, orhasattr(model, "coef_")lies. cached_propertystores its value in the instance dict, so it does not update when the data changes. Use@propertyfor values that must stay in sync.- A class of only static methods is often better as a module of functions.