You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pydantic验证器中@classmethod装饰器的作用疑问

Pydantic验证器中@classmethod装饰器的作用疑问

在Pydantic文档里的很多@field_validator和@model_validator示例中,经常会先给方法加上@classmethod装饰器。文档里有这样一个示例:

from pydantic import (
    BaseModel,
    ValidationError,
    ValidationInfo,
    field_validator,
)


class UserModel(BaseModel):
    name: str
    id: int

    @field_validator('name')
    @classmethod
    def name_must_contain_space(cls, v: str) -> str:
        if ' ' not in v:
            raise ValueError('must contain a space')
        return v.title()

    # you can select multiple fields, or use '*' to select all fields
    @field_validator('id', 'name')
    @classmethod
    def check_alphanumeric(cls, v: str, info: ValidationInfo) -> str:
        if isinstance(v, str):
            # info.field_name is the name of the field being validated
            is_alphanumeric = v.replace(' ', '').isalnum()
            assert is_alphanumeric, f'{info.field_name} must be alphanumeric'
        return v


print(UserModel(name='John Doe', id=1))
#> name='John Doe' id=1

try:
    UserModel(name='samuel', id=1)
except ValidationError as e:
    print(e)

我不太理解@classmethod装饰器的作用。看起来Pydantic的装饰器已经自动把这些方法变成类方法了——我去掉@classmethod装饰器,程序行为完全没变;我甚至在方法里打印cls,发现类依然会被传递给cls参数;就算连@classmethod和cls参数都去掉,模型也能正常工作。那为什么要这么写Pydantic模型呢?只是为了强调这是个类方法吗?在这些函数里访问类又有什么用呢?

备注:内容来源于stack exchange,提问作者oweydd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 08:19:30