I want to create a Pydantic class with a constructor that does some math on inputs and set the object variables accordingly:
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 = ""
But when I try to actually use that class page = PleaseCoorperate(0, 1, 50) I get this error:
main_test.py:16:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
main.py:46: in __init__
self.self0 = ""
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> ???
E AttributeError: __fields_set__
What is happening here? Can I not use constructors on a Pydantic class?
You are not invoking the BaseModel constructor, and thus, you are skipping all the pydantic magic that turns class variables into attributes. This:
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)
should do the trick. However, may I suggest a better option that doesn't override the much excellent default constructor from pydantic with a class method:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With