用值初始化 pydantic List
Inicializing pydantic List with values
我的代码如下所示。但是我不知道如何将 prescibeddrug obejct 插入购物车 class,即 List[PrescribedDrug]。我评论了一些错误的结果。
from pydantic import BaseModel
from typing import List
from typing import Optional
class PrescribedDrug(BaseModel):
ean: str
repayment: str
Cart = List[PrescribedDrug]
drug1 = PrescribedDrug.parse_obj({
"ean": "5055565722000",
"repayment": ""
})
drug2 = PrescribedDrug.parse_obj({
"ean": "5055565722001",
"repayment": ""
})
print(f'type of drug1: {type(drug1)}')
#Cart1 = Cart.__add__(drug1)
#raise AttributeError(attr)
#AttributeError: __add__
#print(Cart1)
#Cart1 = Cart
#Cart1.__add__(drug1)
#print(Cart1)
#raise AttributeError(attr)
#AttributeError: __add__
# Cart1 = Cart
# Cart1.__iadd__([drug1])
# raise AttributeError(attr)
# AttributeError: __iadd__
Cart = List[PrescribedDrug]
是类型,不是列表。
from pydantic import BaseModel
from typing import List
class PrescribedDrug(BaseModel):
ean: str
repayment: str
Cart = List[PrescribedDrug]
drug1 = PrescribedDrug.parse_obj(
{
"ean": "5055565722000",
"repayment": "",
}
)
drug2 = PrescribedDrug.parse_obj(
{
"ean": "5055565722001",
"repayment": "",
}
)
cart: Cart = []
print(f"type of drug1: {type(drug1)}")
cart.append(drug1)
cart.append(drug2)
print(cart)
打印
type of drug1: <class '__main__.PrescribedDrug'>
[PrescribedDrug(ean='5055565722000', repayment=''), PrescribedDrug(ean='5055565722001', repayment='')]
我的代码如下所示。但是我不知道如何将 prescibeddrug obejct 插入购物车 class,即 List[PrescribedDrug]。我评论了一些错误的结果。
from pydantic import BaseModel
from typing import List
from typing import Optional
class PrescribedDrug(BaseModel):
ean: str
repayment: str
Cart = List[PrescribedDrug]
drug1 = PrescribedDrug.parse_obj({
"ean": "5055565722000",
"repayment": ""
})
drug2 = PrescribedDrug.parse_obj({
"ean": "5055565722001",
"repayment": ""
})
print(f'type of drug1: {type(drug1)}')
#Cart1 = Cart.__add__(drug1)
#raise AttributeError(attr)
#AttributeError: __add__
#print(Cart1)
#Cart1 = Cart
#Cart1.__add__(drug1)
#print(Cart1)
#raise AttributeError(attr)
#AttributeError: __add__
# Cart1 = Cart
# Cart1.__iadd__([drug1])
# raise AttributeError(attr)
# AttributeError: __iadd__
Cart = List[PrescribedDrug]
是类型,不是列表。
from pydantic import BaseModel
from typing import List
class PrescribedDrug(BaseModel):
ean: str
repayment: str
Cart = List[PrescribedDrug]
drug1 = PrescribedDrug.parse_obj(
{
"ean": "5055565722000",
"repayment": "",
}
)
drug2 = PrescribedDrug.parse_obj(
{
"ean": "5055565722001",
"repayment": "",
}
)
cart: Cart = []
print(f"type of drug1: {type(drug1)}")
cart.append(drug1)
cart.append(drug2)
print(cart)
打印
type of drug1: <class '__main__.PrescribedDrug'>
[PrescribedDrug(ean='5055565722000', repayment=''), PrescribedDrug(ean='5055565722001', repayment='')]