【发布时间】: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