拥有用户定义对象的 Pydantic 方式

Pydantic way of having user defined object

我是 Pydantic 的新手,我不确定我做错了什么。我已经定义了我的 class 并且它继承自 BaseModel。

class EffectiveCoverage(BaseModel):
    start_date: str
    end_date: str
    env_path: Optional[str] = ""
    supply: Any = None
    effective_coverage: pd.DataFrame = None
    relative_coverage: Dict = dict()
    class_obj: SomeClass = None

它有效,我可以为相同的 class 创建一个对象,但是当我尝试访问供应或 class_obj 时,它抛出一个 AttributeError AttributeError: 'EffectiveCoverage' object has no attribute 'class_obj'

任何帮助将不胜感激:)

您的问题不容易重现。您的示例不完整,但是在添加了一些必需的额外 material 之后(包括 Config,因为 pd.DataFrameSomeClass 没有验证器):

import pandas as pd
from typing import Optional, Any, Dict
from pydantic import BaseModel


class SomeClass:
    pass


class EffectiveCoverage(BaseModel):
    start_date: str
    end_date: str
    env_path: Optional[str] = ""
    supply: Any = None
    effective_coverage: pd.DataFrame = None
    relative_coverage: Dict = dict()
    class_obj: SomeClass = None

    class Config:
        arbitrary_types_allowed = True


ec = EffectiveCoverage(start_date='', end_date='')
print(ec.class_obj)

此代码运行良好,因此您的问题可能与您未共享的部分代码有关。这会打印 None.