我想创建一个带有构造函数的 Pydantic 类,该构造函数对输入进行一些数学运算并相应地设置对象变量:
class PleaseCoorperate(BaseModel):
self0: str
next0: str
def __init__(self, page: int, total: int, size: int):
# Do some math here and later set the values
self.self0 = ""
self.next0 = ""
Run Code Online (Sandbox Code Playgroud)
但是当我尝试实际使用该类时,page = PleaseCoorperate(0, 1, 50)我收到此错误:
main_test.py:16:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
main.py:46: in __init__
self.self0 = ""
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> ???
E AttributeError: __fields_set__
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?我可以不在Pydantic类上使用构造函数吗?
ami*_*ato 14
您没有调用BaseModel构造函数,因此,您跳过了将类变量转换为属性的所有 pydantic 魔法。这:
class PleaseCoorperate(BaseModel):
self0: str
next0: str
def __init__(self, page: int, total: int, size: int):
# Do some math here and later set the values
self0 = ""
next0 = ""
super().__init__(self0=self0, next0=next0)
Run Code Online (Sandbox Code Playgroud)
应该可以解决问题。但是,我可以建议一个更好的选择,它不会使用类方法覆盖 pydantic 中非常优秀的默认构造函数:
class PleaseCoorperate(BaseModel):
self0: str
next0: str
@classmethod
def custom_init(cls, page: int, total: int, size: int):
# Do some math here and later set the values
self0 = ""
next0 = ""
return cls(self0=self0, next0=next0)
x = PleaseCoorperate.custom_init(10, 10, 10)
Run Code Online (Sandbox Code Playgroud)
您可以使用 pydantic 验证器。这些是您解决方案的完美候选者。
from pydantic import BaseModel, validator
class PleaseCoorperate(BaseModel):
self0: str
next0: str
@validator('self0')
def self0_math_test(cls, v): # v set the values passed for self0
# your math here
return new_self0
@validator('next0', always=True) # always if you want to run it even when next0 is not passed (optional)
def next0_must_have(cls, v, values, **kwargs): # values sets other variable values
# your math here
return new_next0
Run Code Online (Sandbox Code Playgroud)
验证器文档:此处