简体   繁体   中英

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 :

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

How do I fix this?

You can define indices in __post_init__ . It will not appear in the repr but it will be accessible as a property.

You also need to have a callable for default_factory , so list instead of [] .

Here is a simplified example (as I do not know what is 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'] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM