Classes and objects
Dataclasses for records
Use generated initialization and readable representations.
Lesson 51 of 63
Reading: about 1 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page5 sections
@dataclass generates common record methods such as __init__ and __repr__. Type annotations describe intended fields but do not validate values at runtime.
Worked example
from dataclasses import dataclass
@dataclass
class Session:
subject: str
minutes: int
item = Session("Python", 25)
print(item.subject, item.minutes)
print(item)Python 25 Session(subject='Python', minutes=25)
Why this works
The decorator builds methods using annotated fields in their declared order. Runtime validation still needs explicit code when required.
Another case
from dataclasses import dataclass, field
@dataclass
class Plan:
sessions: list[int] = field(default_factory=list)
a = Plan()
b = Plan()
a.sessions.append(20)
print(a.sessions, b.sessions)[20] []
Practice
Add a day: int field and construct Session("Python", 25, 1).
Check the practice result
Reveal answer
The instance has day == 1 and its representation includes day=1.
Try another case
Is Session("Python", 25) == Session("Python", 25) True or False?
Check your answer
Reveal answer
True. @dataclass generates an __eq__ method that compares the fields in order.
Your progress
Reveal the check answer or reach the end to complete this lesson.