我想创建一个具有构造函数的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 = ""但是当我尝试实际使用那个类page = PleaseCoorperate(0, 1, 50)时,我得到了这个错误:
main_test.py:16:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
main.py:46: in __init__
self.self0 = ""
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> ???
E AttributeError: __fields_set__这是怎么回事?我不能在Pydantic类上使用构造函数吗?
发布于 2021-04-03 23:35:28
您可以使用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验证器文档:here
发布于 2021-04-03 23:53:28
您没有调用BaseModel构造函数,因此,您跳过了所有将类变量转换为属性的简单魔术。这一点:
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)应该能行得通。然而,我可以建议一个更好的选择,它不会用类方法覆盖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)https://stackoverflow.com/questions/66932842
复制相似问题