Advanced · 12 min
Data classes
Define readable data-focused classes with generated methods.
Declare fields
@dataclass generates an initializer and a useful representation from the annotated fields.
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: int
item = Product("Book", 12)
print(item.price)Output
12
Use defaults safely
A field can have a default value. Required fields still come before fields with defaults.
from dataclasses import dataclass
@dataclass
class Task:
title: str
done: bool = False
print(Task("Test").done)Output
False
Data classes
- Read both data classes examples before answering.
- Run the task, compare its exact output, and revise the code if needed.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Create a booking record
Define Booking as a data class with guest: str, nights: int, and confirmed: bool defaulting to False. Display the supplied booking.
Place @dataclass above the class and annotate all three fields.