不能在 pydantic init 函数中定义变量

con't define variable in pydantic init function

我想定义一个继承自 pydantic BaseModel 的 Base 模型,如下所示

class BaseDomain(BaseModel):

    def __init__(self, **kwargs):
        self.__exceptions = []

    def add_error(self, exception: GeneralException):
        self.__exceptions.append(exception)

但是当我使用继承自 BaseDomain 的产品模型时出现此错误

ValueError: "Product" object has no field "_BaseDomain__exceptions"

因为您覆盖了 pydantic 的 init 方法,该方法在创建继承自 BaseModel 的 class 时执行。你应该调用 super()

def __init__(self, **kwargs):
    super().__init__(**kwargs)
    self.__exceptions = []

编辑

pydantic 似乎会抛出该错误,因为它验证 __exceptions 作为输入并抛出错误,因为它未在 classes annotations[=22 中定义=]

试试这个:

from typing import List, Any

class BaseDomain(BaseModel):
    __exceptions:List[Any] = []

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

请在init方法中引入super

def __init__(self,**kwargs):
super().__init

带有“underscore_attrs_are_private”选项的另一个版本

from typing import List, Optional, Any
from pydantic import BaseModel

class BaseDomain(BaseModel):
    __exceptions: Optional[List[Any]] = None
    class Config:
        underscore_attrs_are_private = True

    def add_error(self, exception: Exception):
        if self.__exceptions is None:
            self.__exceptions = []
        self.__exceptions.append(exception)
        
    def get_exceptions(self):
        return self.__exceptions
        
class Item(BaseDomain):
    name: str

item = Item(name="test")
print(item.get_exceptions())
item.add_error(Exception("test"))
print(item.get_exceptions())