Decorator -- dataclass
dataclass 是 Python 3.7 引入的装饰器,用来 快速定义数据类(data model)。
它的目的:
- 自动生成
__init__、__repr__、__eq__ - 自动可比较、复制
- 强类型支持更好(配合 typing)
- 可读、可维护、代码减少 50% 以上
dataclass = 简洁版的数据模型,替代冗长的 class。
from dataclasses import dataclass
@dataclass
class User:
id: int
name: str
active: bool = True
自动生成:
__init__()
__repr__()
__eq__()
使用:
u = User(1, "Tom")
print(u)
输出:
User(id=1, name='Tom', active=True)
字段必须写类型:
@dataclass
class Point:
x: float
y: float = 0.0
from dataclasses import dataclass, field
@dataclass
class User:
id: int
tags: list = field(default_factory=list)
❗ 为什么不用 tags=[]?
因为可变对象会在所有实例间共享。
开启 order=True:
@dataclass(order=True)
class Score:
value: int
可直接比较:
Score(5) < Score(10)
@dataclass(frozen=True)
class Config:
host: str
port: int
cfg.host = "127.0.0.1"
# ❌ FrozenInstanceError
@dataclass
class Product:
name: str
price: float
def __post_init__(self):
if self.price < 0:
raise ValueError("price cannot be negative")
@dataclass
class User:
id: int
name: str
email: str | None = None
非常适合 FastAPI / ORM / JSON 数据结构。
@dataclass
class Address:
city: str
zip: str
@dataclass
class User:
name: str
address: Address
使用:
u = User("Tom", Address("Beijing", "10000"))
Python 3.10+
from dataclasses import asdict
asdict(u)
输出:
{
"name": "Tom",
"address": {
"city": "Beijing",
"zip": "10000"
}
}
import json
json.dumps(asdict(u), ensure_ascii=False)
@dataclass
class A:
x: int
@dataclass
class B(A):
y: int
| 功能 | dataclass | NamedTuple | Pydantic |
|---|---|---|---|
| 可变性 | 可变 | 不可变 | 可控 |
| 性能 | 很快 | 最快 | 中等 |
| 类型检查 | 依赖 typing | 强 | 强并自动校验 |
| JSON 化 | 手动 | 手动 | 内置 |
| 最适用于 | 业务数据结构 | 简单不可变数据 | API/DB 数据模型 |
@dataclass(
init=True, # 自动生成 __init__
repr=True, # 自动 __repr__
eq=True, # 自动 __eq__
order=False, # 是否可比较
unsafe_hash=False,
frozen=False, # 是否不可变
slots=False, # Python 3.10+: 更省内存
)
from dataclasses import dataclass, field
from typing import List
@dataclass(slots=True) # 更省内存
class NewsItem:
title: str
date: str
tags: List[str] = field(default_factory=list)
from enum import Enum
from dataclasses import dataclass
class Status(Enum):
ACTIVE = "active"
DISABLED = "disabled"
@dataclass
class User:
id: int
status: Status
@dataclass
class UserDTO:
id: int
name: str
用于:
- 接口返回
- DTO(数据传输对象)
- 数据校验
- 业务逻辑层封装
user = User(1, "tom@example.com")
uid, name = user.id, user.name # 手动
# 或
print(*asdict(user).values())
- 比普通 class 更简洁
- 自动生成大量样板代码
- 可维护性好
- 支持类型检查
- 更 Pythonic
- 与现代框架(FastAPI、SQLAlchemy、Pydantic)兼容极好