![](/img/trans.png)
[英]How to get attributes of a class without Pydantic BaseModel?
[英]How to generate attributes dynamically in pydantic?
假設我們有這個名稱列表:
students = ['A','B','C']
我有這個帶有pydantic的model:
class Student(BaseModel):
name: str
rank: int = 0
我有這個 model 我想動態地填充學生並有一個模板:
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"
為什么會這樣? 有更好的方法嗎?
我認為這個問題與沒有在 model 本身中定義學生以及沒有在繼承的 class 上調用__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))
祝你好運,編碼愉快!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.