Dataclasses and property decorator

前端 未结 10 1627
没有蜡笔的小新
没有蜡笔的小新 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 04:51

    Here's another way which allows you to have fields without a leading underscore:

    from dataclasses import dataclass
    
    
    @dataclass
    class Person:
        name: str = property
    
        @name
        def name(self) -> str:
            return self._name
    
        @name.setter
        def name(self, value) -> None:
            self._name = value
    
        def __post_init__(self) -> None:
            if isinstance(self.name, property):
                self.name = 'Default'
    

    The result is:

    print(Person().name)  # Prints: 'Default'
    print(Person('Joel').name)  # Prints: 'Joel'
    print(repr(Person('Jane')))  # Prints: Person(name='Jane')
    

提交回复
热议问题