Concept
Modern `@dataclass`: Boilerplate Elimination
`@dataclass` auto-generates `__init__`, `__repr__`, and `__eq__` methods from type annotations, eliminating repetitive setup.
python
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(10, 20)
print(p) # Point(x=10, y=20) (Auto-generated __repr__!)
print(p == Point(10, 20)) # True (Auto-generated __eq__!)
# 7. Modern `@dataclass`: Boilerplate Elimination `@dataclass` auto-generates `__init__`, `__repr__`, and `__eq__` methods from type annotations, eliminating repetitive setup: ```python from dataclasses import dataclass @dataclass class Point: x: int y: int p = Point(10, 20) print(p) # Point(x=10, y=20) (Auto-generated __repr__!) print(p == Point(10, 20)) # True (Auto-generated __eq__!) ``` Dataclasses are standard in Python 3.7+. If you need an immutable object, pass `@dataclass(frozen=True)` to make instance attributes read-only and hashable for dictionary keys.
Checkpoint
What methods does the `@dataclass` decorator write for you by default?
Practice
Define a dataclass `Item` with fields `name: str` and `cost: float`. Instantiate `i = Item("Potion", 9.99)` and print `i.cost`.
01
Tap code blocks below to assemble
Available Blocks