【问题标题】:Inicializing pydantic List with values用值初始化 pydantic 列表
【发布时间】:2021-07-05 10:47:04
【问题描述】:

我的代码如下所示。但我不知道如何将处方药对象插入到列表 [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] 是一个类型,而不是一个列表。如果你先cart1: Cart = [] 然后cart1.append(drug1) 会发生什么?

标签: python list class pydantic


【解决方案1】:

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='')]

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 2021-12-19
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2021-08-09
    相关资源
    最近更新 更多