Pydantic 的 BaseModel
在 Python 中,使用 BaseModel(通常指 Pydantic 的 BaseModel)和普通的 Python class 主要区别在于数据验证、序列化和类型提示的能力。以下是它们的核心区别:
1. 普通 Python Class(不使用 BaseModel)
class Person:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
特点:
-
无自动数据验证:即使传入错误类型(如
age="abc"),Python 不会报错(除非手动写验证逻辑)。 -
无序列化/反序列化:需手动实现
to_dict()或from_dict()方法。 -
无类型强制转换:即使传入
age="18"(字符串),不会自动转为整数。 -
需手动实现功能:如数据校验、默认值、文档生成等。
2. Pydantic 的 BaseModel
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
特点:
-
自动数据验证:如果类型不匹配(如
age="abc"),会抛出ValidationError。 -
自动类型转换:如
age="18"会自动转为整数18。 -
内置序列化/反序列化:
-
转字典:
person.dict() -
转 JSON:
person.json() -
从字典创建:
Person.parse_raw({"name": "Alice", "age": 20})
-
-
支持默认值和复杂类型:
class Person(BaseModel): name: str = "Anonymous" hobbies: list[str] = [] -
集成 IDE 支持:类型提示(如 VS Code 的自动补全)。
-
与 FastAPI 深度集成:请求/响应数据的自动处理。
关键区别总结
| 特性 | 普通 Class | Pydantic BaseModel |
|---|---|---|
| 类型验证 | 需手动实现 | 自动验证并报错 |
| 类型强制转换 | 无 | 自动(如 "18" → 18) |
| 序列化/反序列化 | 需手动实现 | 内置方法(.dict(), .json()) |
| 默认值 | 需在 __init__ 中定义 |
直接声明字段时设置 |
| FastAPI 集成 | 不直接支持 | 自动处理请求/响应数据 |
| 复杂类型(如 UUID, datetime) | 需手动处理 | 内置支持 |
何时使用哪种?
-
用普通
class:-
不需要数据验证或序列化。
-
实现纯业务逻辑(如算法、工具类)。
-
-
用
BaseModel:-
处理外部输入(如 API 请求、配置文件)。
-
需要类型验证和自动转换。
-
与 FastAPI、FastAPI 或其他框架集成。
-
示例对比
普通 Class(需手动验证)
p = Person(name="Alice", age="20") # 不会报错,但 age 是字符串
if not isinstance(p.age, int):
raise ValueError("Age must be an integer") # 需手动检查
Pydantic(自动验证)
p = Person(name="Alice", age="20") # 自动转为 age=20(int)
p = Person(name="Alice", age="abc") # 报错:ValidationError
FastAPI 中的实际应用
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
async def create_item(item: Item): # FastAPI 自动验证请求体
return {"item": item.dict()}
-
如果请求的 JSON 不符合
Item模型,FastAPI 会直接返回 422 错误。
总结:BaseModel 是专门为数据验证和序列化设计的工具,而普通 class 更适用于通用编程。在涉及数据输入/输出的场景(如 API 开发),优先使用 BaseModel。

浙公网安备 33010602011771号