capypad
0 day streak
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
python
1
2
3
4
5
6
7
8
9
10
from dataclasses import dataclass
 
@dataclass
class Product:
name: str
price: float
quantity: int = 0
 
def 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.