python · level 3 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A dataclass and a plain class. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
class Spot:
def __init__(self, x, y):
self.x = x
self.y = y
print(Point(1, 2) == Point(1, 2), Spot(1, 2) == Spot(1, 2))
print(Point(3, 4))
your turn
Your turn. Describe a library book.
Give on_loan the default False. Then make a book with a title, an author and a page count of your choice.
fix it
Python refuses to make the playlist. Fix it!
- Read the error: Python refuses a list as a plain default. What does it suggest instead?
- A plain
[]default would be shared by every playlist. Ask for a fresh list each time. - Change
= []to= field(default_factory=list), then run.
nailed it
your classes write themselves now. :D
@dataclasswrites__init__, a print-out and==from your fields.- Use
field(default_factory=list)for list or dictionary defaults. frozen=Truelocks the fields once the object exists.
new words in your collection
- dataclass
- field
- frozen
This lesson isn’t saved. A free account remembers every lesson you finish.