×

python · level 3 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A writes the boring parts of a class for you.

Most classes start the same way: an __init__ that copies every argument into self. Put @dataclass above the class and list each with a type hint. Python writes __init__ for you, plus a readable print-out and an == that compares fields.

Give a field a default with =. For a list default, write field(default_factory=list), so every object gets its own fresh list.

Add and fields cannot change after the object is made, so accidental changes become errors.

from dataclasses import dataclass, field

@dataclass
class Order:
    customer: str
    total: int = 0
    items: list[str] = field(default_factory=list)

first = Order("Sam")
first.items.append("bagel")
second = Order("Ana", 450, ["wrap"])
print(first)
print(second == Order("Ana", 450, ["wrap"]))

Fields with defaults must come after fields without, like parameters in a def line.