使用dataclasses构造数据类

官方文档


使用场景:

  当创建的类要初始化的变量很多时(即一个数据类),如:

class StarWarsMovie:
    def __init__(self,
                producer: str,
                release_date: datetime,
                characters: List[str],
                planets: List[str],
                starships: List[str],
                vehicles: List[str],
                species: List[str],
                created: datetime,
                edited: datetime,
                url: str
                ):

        self.producer = producer
        self.release_date = release_date
        self.characters = characters
        self.planets = planets
        self.starships = starships
        self.vehicles = vehicles
        self.species = species
        self.created = created
        self.edited = edited
        self.url = url

        if type(self.release_date) is str:
            self.release_date = dateutil.parser.parse(self.release_date)
    
        if type(self.created) is str:
            self.created = dateutil.parser.parse(self.created)
    
        if type(self.edited) is str:
            self.edited = dateutil.parser.parse(self.edited)

  可以看到有很多重复的代码,避免这种情况可以使用dataclass装饰器

  使用dataclass装饰器后:

from dataclasses import dataclass
@dataclass
class StarWarsMovie: producer: str release_date: datetime characters: List[str] planets: List[str] starships: List[str] vehicles: List[str] species: List[str] created: datetime edited: datetime url: str def __post_init__(self): if type(self.release_date) is str: self.release_date = dateutil.parser.parse(self.release_date) if type(self.created) is str: self.created = dateutil.parser.parse(self.created) if type(self.edited) is str: self.edited = dateutil.parser.parse(self.edited)

  dataclass 自动生成一些 dunder 方法(即带双下划线的方法),如果我们没有为 data class 装饰器指定任何选项,

  则生成的方法有:__init__,__eq__和__repr__

  如果在类上定义了 __post_init__() ,自动生成的__init__方法将调用这个__post_init__

  要初始化的参数也将按照它们在类中定义的顺序传递给 __post_init__()


dataclass装饰器也可以自定义要自动生成的方法,具体方式参考官方文档

 

 

posted @ 2021-01-21 11:53  Pio-GD  阅读(217)  评论(0编辑  收藏  举报