python / intermediate
Snippet
Simplifying Classes with Dataclasses
The @dataclass decorator automatically generates common methods like __init__, __repr__, and __eq__ based on type hints, reducing boilerplate code in data-oriented classes.
snippet.py
1
2
3
4
5
6
7
8
9
10
from dataclasses import dataclass@dataclassclass Product:name: strprice: floatquantity: int = 0def total_value(self) -> float:return self.price * self.quantity
Breakdown
1
@dataclass
Instructs Python to generate standard methods for the class automatically.
2
name: str
Defines a field with a type hint, which dataclass uses to build the constructor.