简体   繁体   English

使用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

In the code above, I get this error for the line indices:List[str] = [vi] + bands :在上面的代码中,我收到以下行indices:List[str] = [vi] + bands错误indices:List[str] = [vi] + bands

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

How do I fix this?我该如何解决?

You can define indices in __post_init__ .您可以在__post_init__定义indices It will not appear in the repr but it will be accessible as a property.它不会出现在repr但可以作为属性访问。

You also need to have a callable for default_factory , so list instead of [] .您还需要有一个可调用的default_factory ,所以list而不是[]

Here is a simplified example (as I do not know what is setup :这是一个简化的示例(因为我不知道是什么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'] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Django 模型中使用 Python 数据类 - Using Python Dataclass in Django Models Python 3.7:数据类不会为 `eq=False` 引发 `TypeError` - Python 3.7: dataclass does not raise `TypeError` for `eq=False` 如何在 Python 中修复数据类的 TypeError? - How can I fix the TypeError of my dataclass in Python? 如何在 Python 中的数据类实例化期间将字符串转换为枚举 - How to cast a string to an Enum during instantiation of a dataclass in Python 使用基础实例 Python 继承数据类 - Inherite dataclass using base instance Python python gensim word2vec给出TypeError TypeError:类型'generator'的对象在自定义数据类上没有len() - python gensim word2vec gives typeerror TypeError: object of type 'generator' has no len() on custom dataclass 使用Python数据类时,哪里是处理数据以初始化数据类的正确位置 - When using Python dataclass where is the correct place to process the data for initializing the dataclass TypeError:并非使用MySQL和Python在字符串格式化期间转换所有参数 - TypeError: not all arguments converted during string formatting using MySQL and Python 将参数传递给数据类会导致 TypeError - Passing the arguments to dataclass causes TypeError Python 使用数据类将基础 class object 转换为子类 - Python casting base class object to subclass using dataclass
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM