How to use the __post_init__ method in Dataclasses in Python

后端 未结 1 1606
無奈伤痛
無奈伤痛 2021-01-27 11:14

I am trying to get my hands dirty with dataclasses in Python and what i want to do is have a computed field inside my class and also add the sort_index field to the call but wou

相关标签:
1条回答
  • 2021-01-27 11:56

    The problem is you are trying to set a field of a frozen object. There are two options here. First option would be to remove frozen=True from the dataclass specification. Secondly, if you still want to freeze Person instances, then you should initialize fields with method __set_atr__. Therefore, your post_init method will become:

    def __post_init__(self):
        self.__setattr__('sort_index', self.age)
        self.__setattr__('birthyear', _get_year_of_birth(self.age)
    
    0 讨论(0)
提交回复
热议问题