Since version 3.7, Python offers data classes. There are several advantages over regular classes or other alternatives, like returning multiple values using a tuple or dictionaries:
- A data class requires a minimal amount of code
- You can compare data classes because
__eq__is implemented for you - You can easily print a data class for debugging because
__repr__is implemented as well - Data classes require type hints, reducing the chances of bugs
Here’s an example of a data class at work:
from dataclasses import dataclass
@dataclass
class Card:
rank: str
suit: str
card = Card("Q", "hearts")
print(card == card)
# True
print(card.rank)
# 'Q'
print(card)
Card(rank='Q', suit='hearts')
