Python
Topic 15 · Writing real programs · ⏱ about 4 h

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.

Show:
In this topic
Beginner

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).

Beginner

Defining a class: __init__, attributes and methods

class Account: interest = 0.02 # class attribute: shared by all accounts def __init__(self, owner, balance=0): self.owner = owner # instance attributes: one per object self.balance = balance def deposit(self, amount): if amount <= 0: raise ValueError("amount must be positive") self.balance += amount return self.balance a = Account("Sita") # Python calls __init__(a, "Sita") a.deposit(100) # Python calls Account.deposit(a, 100)

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

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.

Beginner

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:

from dataclasses import dataclass @dataclass class Patient: id: int name: str age: int | None = None
Beginner

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)), whose fit method learns from data and stores results as attributes ending in underscore (model.coef_), and whose predict method uses them.
  • A PyTorch network is a class that inherits from nn.Module: you define its layers in __init__ and the calculation in forward.
Beginner

Code: a small class and a dataclass

A model-like class with fit and predict, inheritance with super(), and a dataclass.

Python
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])
Open in playground ↗
Beginner

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.

Exercise 1. A BankAccount class

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.

Exercise 2. A readable object

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).

Beginner

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 self as the first parameter of a method.
  • Writing name = name in __init__ instead of self.name = name.
  • Calling the class without brackets: Dog is the class, Dog() makes an object.
Check yourself

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?

Go deeper

📚 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.

Ready