
Code
Dataclasses: Less Typing
Many classes are mostly data: a quest has a title, a reward, some
tags. Writing __init__, __repr__ and __eq__ for each one gets
old fast. The @dataclass decorator writes them for you from a list
of annotated fields:
from dataclasses import dataclass, field
@dataclass
class Bridge:
start: str
end: str
length: int = 10 # default value
planks: list = field(default_factory=list)
b = Bridge("Mossreach", "Ashfall")
print(b) # Bridge(start='Mossreach', end='Ashfall', length=10, planks=[])
print(b == Bridge("Mossreach", "Ashfall")) # True
Rules worth remembering:
- Every field needs a type annotation (
name: type). - Fields with defaults must come after fields without.
- Never write
planks: list = []. Mutable defaults needfield(default_factory=list)so every object gets a fresh list (dataclasses even raise an error if you forget). - You can still add your own methods.
Assignment
Turn Quest into a dataclass with these fields, in this order:
title: str(no default)reward: int, default10tags: list, default a new empty listdone: bool, defaultFalse
Then finish complete(): set done to True and return the reward.
Turn Quest into a dataclass with these fields, in this order:
title: str(no default)reward: int, default10tags: list, default a new empty listdone: bool, defaultFalse
Then finish complete(): set done to True and return the reward.
main.py Python sleeping
Press Run to try your code, then Check to test it.