使用 python 数据类时出现类型错误

TypeError during using python dataclass

@dataclass
class cntr(setup):
    source:str = 'S2'
    vi:str = 'SW'
    # Dataframe containing information on samples
    df:pd.DataFrame = pd.DataFrame()

    # Available bands
    bands:List[str] = field(default_factory=[])

    indices:List[str] = [vi] + bands

在上面的代码中,indices:List[str] = [vi] + bands:

行出现此错误

*** TypeError: can only concatenate list (not "Field") to list

我该如何解决这个问题?

您可以在__post_init__中定义indices。它不会出现在 repr 中,但可以作为 属性.

访问

您还需要 default_factory 的可调用对象,因此 list 而不是 []

这是一个简化的例子(因为我不知道什么是 setup:

@dataclass
class cntr():
    source:str = 'S2'
    vi:str = 'SW'
    # Available bands
    bands:List[str] = field(default_factory=list)

    def __post_init__(self):
        self.indices:List[str] = [self.vi] + self.bands
c = cntr()
c.indices  # will print: ['SW']