6

我有以下数据类。

@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]

以及调用上述类的以下数据类。

@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:泛型类型的参数必须是类型。

我也试过用_destinations这种方式给会员打电话。

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

然后我收到以下错误

TypeError:泛型类型的参数必须是类型。

我也尝试将班级成员设置为

    _destinations: [] 

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

我也试过。

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

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

AttributeError:“DestinationContainer”对象没有属性“_destinations”

4

1 回答 1

7

正如帕特里克在评论中所说,您的主要问题是您__init__在使用@dataclass. 如果您删除它并稍微重组您的代码,它应该可以按预期工作:

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']))
于 2019-03-11T08:13:18.537 回答