🏗️ Classes & Objects, lesson 6 of 6
Dataclasses
Skip the boilerplate: auto-generated __init__, __repr__ and ==.
9 min
1 exercise
1 quiz
0/2 solved
Getting Python ready… examples can run in a moment.
Many classes mostly hold data, and writing
__init__, __repr__ and __eq__ by hand gets
repetitive. The @dataclass decorator writes them
for you from a list of fields:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
The : int parts are type hints. Python doesn't
enforce them, but dataclasses use them to find the
fields.
A dataclass in action
You got __init__, a readable __repr__ and
value-based == for free. Fields with defaults must
come after fields without one.
What does this print?
A dataclass is still a normal class: add methods and properties as usual.
For list or dict fields, use
field(default_factory=list). Dataclasses refuse
tags: list = [] to protect you from the shared-list
trap you saw earlier.
Methods and default_factory
Replace field(default_factory=list) with [] and
run it: Python stops you with a ValueError.
Options worth knowing:
@dataclass(order=True)adds<,>and friends, comparing fields in order, so sorting works@dataclass(frozen=True)makes objects read-only, and hashable, so they can go in sets
Sortable, frozen versions
As text, "1.10" sorts before "1.2", but comparing
number fields gets it right. Try
vs[0].major = 2 to see frozen in action.
Inventory report
- Turn
Productinto a dataclass with fieldsname: str,price: floatandqty: int = 0. - Add a method
total_value()that returnsprice * qty. - Set
inventory_valueto the sum oftotal_value()overstock, rounded to 2 decimals.