Force type conversion in python dataclass __init__ method

前端 未结 3 1992
孤城傲影
孤城傲影 2021-01-07 20:43

I have the following very simple dataclass:

import dataclasses

@dataclasses.dataclass
class Test:
    value: int

I create an instance of t

3条回答
  •  梦毁少年i
    2021-01-07 21:32

    You could achieve this using the __post_init__ method:

    import dataclasses
    
    @dataclasses.dataclass
    class Test:
        value : int
    
        def __post_init__(self):
            self.value = int(self.value)
    

    This method is called following the __init__ method

    https://docs.python.org/3/library/dataclasses.html#post-init-processing

提交回复
热议问题