appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Classes and dataclasses

Lesson 1 of 511 minIntermediate

Bundle data and behaviour, and let dataclasses write the boilerplate.

A class describes a kind of object: the data it holds (attributes) and what it can do (methods). An instance is one object made from it.

class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        self.balance += amount

acc = Account("Ana")
acc.deposit(50)
print(acc.balance)   # 50
  • __init__ runs when you create the instance.
  • self is the instance. It is always the first parameter of a method.
  • Methods named with double underscores (__repr__, __eq__) are special methods that customise built-in behaviour.

Dataclasses

For classes that mostly hold data, @dataclass generates __init__, __repr__ and __eq__ from the annotated fields.

from dataclasses import dataclass, field

@dataclass
class Order:
    id: int
    items: list[str] = field(default_factory=list)
    paid: bool = False

o = Order(1)
print(o)   # Order(id=1, items=[], paid=False)

CarefulNever use a mutable default such as items: list = []. All instances would share the same list. Use field(default_factory=list). The same rule applies to default arguments of functions.

NoteAdd frozen=True to make instances immutable, which is useful for values you use as dictionary keys.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What is self in a method?
2. Why is items: list = [] a bug in a dataclass?
3. What does @dataclass generate for you?

Key terms