Skip to content
Streak:0Loading your progress…Sign in

Module 4 · Lesson 1 of 3

Classes & dataclasses

Explicit self, dunder methods, and @dataclass as Python's data class. ~25 min

Lesson notes

Coming from Dart

Dart

class Point {
  final int x, y;
  const Point(this.x, this.y);
  @override String toString() => 'Point($x, $y)';
}

Python

from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: int
    y: int
# __init__, __repr__, __eq__ (and __hash__ when frozen) generated

frozen=True is like Dart's final fields — instances are immutable and hashable.

Plain classes: self is explicit; dunder methods hook into language syntax
class Money:
    def __init__(self, cents: int, currency: str = "AUD"):
        self.cents = cents
        self.currency = currency

    def __add__(self, other: "Money") -> "Money":
        if other.currency != self.currency:
            raise ValueError("currency mismatch")
        return Money(self.cents + other.cents, self.currency)

    def __repr__(self) -> str:
        return f"Money({self.cents}, {self.currency!r})"

There are no access modifiers. Convention: a leading underscore (_cache) means "internal". @property gives you computed getters like Dart's get.

Practice

  1. 1. Shopping cart with dataclasses

    medium25 XP

    Create a frozen dataclass Item(name: str, price_cents: int, qty: int = 1) and a dataclass Cart with an items: list[Item] field defaulting to an empty list. Give Cart a method add(item) and a @property total_cents.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor