@dataclass tự động generate __init__, __repr__, __eq__ — giảm boilerplate đáng kể.
python
from dataclasses import dataclass, field
from typing import List
@dataclass
class User:
name: str
email: str
age: int = 0
tags: List[str] = field(default_factory=list)
# __init__, __repr__, __eq__ tự động được generate!
@dataclass(frozen=True) # Immutable như tuple
class Point:
x: float
y: float
p = Point(1.0, 2.0)
# p.x = 3.0 # FrozenInstanceErrorƯu điểm so với namedtuple: có default values, methods, mutable (nếu không frozen).
@dataclass auto-generates __init__, __repr__, __eq__ — reduces boilerplate significantly.
python
@dataclass
class Config:
host: str = 'localhost'
port: int = 8080
debug: bool = False
# Equivalent to writing __init__, __repr__, __eq__ manually
c = Config(port=3000)
print(c) # Config(host='localhost', port=3000, debug=False)