【问题标题】:How to generate attributes dynamically in pydantic?如何在pydantic中动态生成属性?
【发布时间】:2021-07-28 10:14:15
【问题描述】:

假设我们有这个名字列表:

students = ['A','B','C']

我有这个带有 pydantic 的模型:

class Student(BaseModel):
    name: str
    rank: int = 0

我有这个模型,我想动态地在其中填充学生,并且像模板一样:

class MathClass(BaseModel):
    def __init__(self, student_names):
        self.students = []
        for student_name in student_names:
             self.students.append(Student(name=student_name))

当我使用

启动我的代码时
math_class=MathClass(students)

我收到此错误:

ValueError: "MathClass" object has no field "students"

为什么会这样?有更好的方法吗?

【问题讨论】:

    标签: python oop attributes pydantic


    【解决方案1】:

    我认为这个问题与没有在模型本身中定义学生以及没有在继承的类上调用 __init__() 有关。我可以通过像这样修改MathClass 来运行您的代码:

    class MathClass(BaseModel):
       students: list = []
        
       def __init__(self, student_names: list):
            super().__init__()
    
            for student_name in student_names:
                self.students.append(Student(name=student_name))
    

    祝你好运,编码愉快!

    【讨论】:

    • 成功了!谢谢 :) 为什么我要在继承的类上调用 init 呢?
    • 好问题!我们需要显式调用继承类的构造函数,即使您从 BaseModel 继承,类似于其他 OOPL。我对 pydantic 不太熟悉,所以我不确定它在幕后做了什么。
    猜你喜欢
    • 1970-01-01
    • 2014-04-08
    • 2014-10-18
    • 2022-08-16
    • 2016-01-05
    • 2015-11-03
    • 2020-10-29
    • 1970-01-01
    • 2012-10-19
    相关资源
    最近更新 更多