Dataclasses and property decorator

前端 未结 10 1665
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 04:43

I\'ve been reading up on Python 3.7\'s dataclass as an alternative to namedtuples (what I typically use when having to group data in a structure). I was wondering if datacla

10条回答
  •  盖世英雄少女心
    2020-12-15 05:14

    After trying different suggestions from this thread I've come with a little modified version of @Samsara Apathika answer. In short: I removed the "underscore" field variable from the __init__ (so it is available for internal use, but not seen by asdict() or by __dataclass_fields__).

    from dataclasses import dataclass, InitVar, field, asdict
    
    @dataclass
    class D:
        a: float = 10.                # Normal attribut with a default value
        b: InitVar[float] = 20.       # init-only attribute with a default value 
        c: float = field(init=False)  # an attribute that will be defined in __post_init__
        
        def __post_init__(self, b):
            if not isinstance(getattr(D, "a", False), property):
                print('setting `a` to property')
                self._a = self.a
                D.a = property(D._get_a, D._set_a)
            
            print('setting `c`')
            self.c = self.a + b
            self.d = 50.
        
        def _get_a(self):
            print('in the getter')
            return self._a
        
        def _set_a(self, val):
            print('in the setter')
            self._a = val
    
    
    if __name__ == "__main__":
        d1 = D()
        print(asdict(d1))
        print('\n')
        d2 = D()
        print(asdict(d2))
    
    

    Gives:

    setting `a` to property
    setting `c`
    in the getter
    in the getter
    {'a': 10.0, 'c': 30.0}
    
    
    in the setter
    setting `c`
    in the getter
    in the getter
    {'a': 10.0, 'c': 30.0}
    

提交回复
热议问题