MrFaws Docs
Learn Python

Object-Oriented Python

Classes, dataclasses, composition, inheritance and clear interfaces.

Objects are useful when data and behavior naturally belong together. Prefer a function and a dictionary when they are simpler.

class BankAccount:
    def __init__(self, owner: str, balance: int = 0) -> None:
        self.owner = owner
        self._balance = balance

    def deposit(self, amount: int) -> None:
        if amount <= 0:
            raise ValueError("Amount must be positive")
        self._balance += amount

    @property
    def balance(self) -> int:
        return self._balance

Dataclasses

from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class User:
    id: int
    name: str
    roles: tuple[str, ...] = field(default_factory=tuple)

Prefer composition

Give a service the dependencies it needs instead of inheriting from them. Composition makes implementations easier to replace and test. Use inheritance for a genuine and stable “is a” relationship; use Protocol when different objects only need to provide the same methods.

Exercise

Build an inventory with Product, Inventory and a replaceable Storage interface. Add memory and JSON storage without modifying the inventory rules.

On this page