Classes & Objects
Bundle data and behaviour into classes: __init__, attributes, methods, special methods, inheritance, dataclasses, and how scikit-learn models and PyTorch networks are classes you already use.
Why classes?
A class is a blueprint; an object (or instance) is one thing built from it. A class bundles data (attributes) with the functions that work on that data (methods). You have used objects from the start: a string has .upper(), a list has .append(), a scikit-learn model has .fit() and .predict().
Write a class when several functions keep passing the same group of values around, or when you need many similar things that each keep their own state (many bank accounts, many training runs).
Defining a class: __init__, attributes and methods
self is the object the method was called on. Python passes it automatically: a.deposit(100) becomes Account.deposit(a, 100). __init__ runs when you create an object and sets up its attributes.
Try it: objects keep their own state
Create accounts and call their methods. Each object keeps its own balance; the class attribute is shared.
Interactive: this part runs in your browser.
Special methods, inheritance and dataclasses
Methods with double underscores ("dunder" methods) hook your class into Python's syntax: __repr__ controls how it prints, __len__ makes len(obj) work, __eq__ defines ==.
Inheritance makes a class that reuses and extends another: class SavingsAccount(Account): gets every method of Account, can add new ones, and can override existing ones (calling the original with super()). Prefer shallow hierarchies; often it is simpler to have an object contain another (composition).
For classes that mainly hold data, a dataclass writes __init__, __repr__ and __eq__ for you:
Classes you already use
Machine-learning libraries are built from classes, and knowing that makes them far less mysterious:
- A scikit-learn model is an object whose
__init__stores settings (LogisticRegression(C=0.5)), whosefitmethod learns from data and stores results as attributes ending in underscore (model.coef_), and whosepredictmethod uses them. - A PyTorch network is a class that inherits from
nn.Module: you define its layers in__init__and the calculation inforward.
Code: a small class and a dataclass
A model-like class with fit and predict, inheritance with super(), and a dataclass.
from dataclasses import dataclass
class MeanPredictor:
"""Predicts the average of the training targets: the simplest baseline model."""
def __init__(self, digits=2):
self.digits = digits
def fit(self, y):
self.mean_ = round(sum(y) / len(y), self.digits) # learned value, ends in _
return self # allows chaining
def predict(self, n):
return [self.mean_] * n
def __repr__(self):
return f"MeanPredictor(digits={self.digits})"
m = MeanPredictor().fit([3, 5, 10])
print(m, m.mean_, m.predict(3))
class MedianPredictor(MeanPredictor): # inherits predict and __init__
def fit(self, y):
s = sorted(y)
mid = len(s) // 2
self.mean_ = s[mid] if len(s) % 2 else (s[mid - 1] + s[mid]) / 2
return self
print(MedianPredictor().fit([3, 5, 100]).predict(2))
@dataclass
class Run:
name: str
lr: float
accuracy: float = 0.0
runs = [Run("a", 0.1, 0.81), Run("b", 0.01, 0.86)]
print(max(runs, key=lambda r: r.accuracy))
print(Run("a", 0.1, 0.81) == runs[0])Practice: check yourself
Write the code, then press ✔ Check my answer: hidden tests run your code and tell you exactly what is right. ▶ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.
Write a class BankAccount with __init__(self, owner) (balance starts at 0), deposit(self, amount) and withdraw(self, amount). Withdrawing more than the balance must raise ValueError and leave the balance unchanged.
Give the Point class a __str__ method so that str(Point(3, 4)) is "(3, 4)", and a method distance_to_origin() that returns 5.0 for Point(3, 4).
Summary
Key words
- class
- a blueprint for making objects
- object / instance
- one thing made from a class
- attribute
- a value stored on an object:
self.name - method
- a function defined in a class
__init__- the method that sets up a new object
- inheritance
- a class that extends another class
Common mistakes
- Forgetting
selfas the first parameter of a method. - Writing
name = namein__init__instead ofself.name = name. - Calling the class without brackets:
Dogis the class,Dog()makes an object.
Quiz
1. What is self in a method?
2. When does __init__ run?
3. In scikit-learn, attributes ending in an underscore like coef_ are…
4. What does @dataclass give you?
📚 Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- The Python Tutorial: Classes ↗ classes, inheritance, iterators and generators
- Think Python, 3rd edition (Allen Downey) ↗ free online textbook that teaches thinking like a programmer