【问题标题】:How to declare an array or a list in a Python @dataclass? [duplicate]如何在 Python @dataclass 中声明数组或列表? [复制]
【发布时间】:2020-01-01 14:00:28
【问题描述】:

如何在@dataclass 中声明一个数组(或至少是一个列表)?如下所示:

from dataclasses import dataclass

@dataclass
class Test():
    my_array: Array[ChildType]

【问题讨论】:

  • my_array: list?或者List[...],如果你想指定元素类型。但是您必须从正确的位置导入这些东西 - dataclass 不在 abc 中。

标签: python python-3.x python-dataclasses python-typing type-hinting


【解决方案1】:

没有Array数据类型,但可以指定my_array的类型为typing.List

from dataclasses import dataclass
from typing import List

@dataclass
class Test:
    my_array: List[ChildType]

从 Python 3.9 开始,您可以方便地使用 list

from dataclasses import dataclass

@dataclass
class Test:
    my_array: list[ChildType]

【讨论】:

  • 感谢您的回答,我已经更新了问题。我认为它具有主要类型
  • @Шах 编辑了我的答案以删除无用的ABC 东西。
猜你喜欢
  • 2020-04-01
  • 1970-01-01
  • 2011-05-02
  • 2012-02-26
  • 2012-04-01
  • 1970-01-01
  • 2016-11-17
  • 2018-10-22
  • 2014-01-05
相关资源
最近更新 更多