通过元素扩展类型列表的数据类

expanding a dataclass of type list by an element

我定义了一个数据类,它是一个列表,我想扩展它:

@dataclass
class ShoppingCart:
    item_id: list = None

@dataclass
class Purchase:
    items: dict = ShoppingCart

@dataclass
class Item:
    price: int = 0
    name: str = ""

所以稍后我将一件商品放入购物车:

if getattr(inst_of_Purchase, inst_of_ShoppingCart) == None: ##no item in cart
    setattr(inst_of_Purchase, inst_of_ShoppingCart, inst_of_Item)
else: ## add an item
    ***

追加项目以获得如下结构的正确语法是什么:

Purchase_1: {ShoppingCart_1: [item_1, item_2 ...], 
             ShoppingCart_2: [item_123, item_2 ...]...}
    

以下是我声明模型的方式,使用前向引用以便更容易看到嵌套结构(自上而下而不是自下而上)。如果您想像最初那样采用自下而上的方法,则可以交换定义数据类的顺序并将 List['ShoppingCart'] 切换为 List[ShoppingCart] 例如。

from dataclasses import dataclass
from typing import List


@dataclass
class Purchase:
    carts: List['ShoppingCart'] = None


@dataclass
class ShoppingCart:
    # If you want default value to be an empty list:
    #  item: List['Item'] = dataclasses.field(default_factory=list)
    items: List['Item'] = None


@dataclass
class Item:
    price: int = 0
    name: str = ""

然后如果我们需要将项目添加到新购买:

my_purchase = Purchase()

if my_purchase.carts is None:  # no item in cart
    item_1 = Item(name='first item')
    item_2 = Item(2, 'second item')

    my_cart = ShoppingCart(items=[item_1, item_2])
    my_purchase.carts = [my_cart]

else: ## add an item
    ...

print(my_purchase)
# Purchase(carts=[ShoppingCart(items=[Item(price=0, name='first item'), Item(price=2, name='second item')])])

请注意,如果您使用的是 Python 3.9+(我不确定您是不是),您可以删除 typing.List 导入,并使用内置的 list ,因为标准集合现在支持下标类型。因此,例如,取自以上内容:

carts: List['ShoppingCart'] = None

将变成(没有 typing 导入):

carts: list['ShoppingCart'] = None