如何在 Python 3.7.x 中将列表[customClass] 用作@dataclass 的类型

How can I use a list[customClass] as type with @dataclass in Python 3.7.x

我有以下数据classes.

@dataclass
class Package:
    '''Class for keeping track of one destination.'''
    _address: []

@dataclass
class Destination:
'''Class for keeping track of a destination.'''
_start: str
_end: str
_distance: float

def __init__(self, param):
    self._start = param[0]
    self._end = param[1]
    self._distance = param[2]

和下面的数据class调用上面的class.

@dataclass
class DestinationContainer:
    '''Class for keeping track of a package destination.
       and all the possible combinations of potential next destination '''
    _package: Package
    _destinations: List[Destination]

    def __init__(self):
        pass

    def addPkg(self,param):
        self._package = param

尝试运行程序

时出现以下错误

TypeError: Parameters to generic types must be types.

我也试过这样给_destinations会员打电话

_destinations: List[Destination] = field(default_factory=list)

然后我得到以下错误

TypeError: Parameters to generic types must be types.

我也试过将 class 成员设置为

    _destinations: [] 

并且在检查实例对象时,class 中没有可用的列表。

我也试过了。

_destinations: List = field(default_factory=lambda: [])

尝试添加到列表时出现以下错误

AttributeError: 'DestinationContainer' object has no attribute '_destinations'

正如 Patrick 在评论中所说,您的主要问题是您在使用 @dataclass 时定义了自己的 __init__ 函数。如果您删除它并稍微重组您的代码,它应该会按预期工作:

from dataclasses import dataclass
from typing import List

@dataclass
class Package:
    _address: List[str]

@dataclass
class Destination:
    _start: str
    _end: str
    _distance: float

@dataclass
class DestinationContainer:
    _package: Package
    _destinations: List[Destination]

    def addPkg(self, param):
        # sure this shouldn't be "self._package.append(param)"? 
        self._package = param


# works
dc = DestinationContainer(
    Package(['some address']),
    [Destination('s', 'e', 1.0)]
)
# also works
dc.addPkg(Package(['some other address']))