What are Data Classes?
Data classes (Python 3.7+) reduce boilerplate for classes that primarily store data. They auto-generate __init__, __repr__, __eq__, and more.
Basic Data Class
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
p = Point(3.0, 4.0)
print(p) # Point(x=3.0, y=4.0)
print(p == Point(3.0, 4.0)) # True
With Methods
@dataclass
class Rectangle:
width: float
height: float
def area(self) -> float:
return self.width * self.height
rect = Rectangle(10, 5)
print(rect.area()) # 50
Immutable
@dataclass(frozen=True)
class Color:
r: int
g: int
b: int
red = Color(255, 0, 0)
# red.r = 100 # Error!
Summary
- @dataclass auto-generates __init__, __repr__, __eq__
- Use frozen=True for immutable objects
- field() provides default_factory and other options
YouTip