可以为Python数据类创建默认的初始化程序,以初始化2D数组,即与
相同from dataclasses import dataclass, field
from typing import List
MAX = 5
@dataclass
class AlgoData:
list2D: List[List[int]] # = ???
list1D: List[int] = field(default_factory=list)
b = [[] for m in range(MAX)]
a = AlgoData(b)
,但没有b
参数。结果:
AlgoData(list2D=[[], [], [], [], []], list1D=[])
答案 0 :(得分:3)
您可以使用lambda
函数代替default_factory
的{{1}}:
field
from dataclasses import dataclass, field
from typing import List
MAX = 5
@dataclass
class AlgoData:
list2D: List[List[int]] = field(default_factory=lambda: [[] for m in range(MAX)])
list1D: List[int] = field(default_factory=list)
a = AlgoData()
变为:
a
答案 1 :(得分:0)
另一种选择是在初始化后(通过__post_init__
)分配属性 。
给出
from typing import List
from dataclasses import dataclass, field
MAX = 5
代码
@dataclass
class AlgoData:
"""Algorithm data."""
list1D: List[int] = None
list2D: List[List[int]] = field(default_factory=list)
def __post_init__(self):
self.list2D = [[] for _ in range(MAX)]
演示
a = AlgoData()
a
# AlgoData(list2D=[[], [], [], [], []], list1D=[])