[Python] Use of python property decorator for non-class attributes

Discussão em 'Python' iniciado por Stack, Setembro 26, 2024.

  1. Stack

    Stack Membro Participativo

    Simple one that's been annoying me when I see it: Is it correct or pythonic to use the property decorator outside the getter/setter context where you are not returning a protected class attribute. For example:

    class ExampleWithUnnecessaryProperty:

    def __init__(self, a: str):
    self._a = a # protected attribute

    # This feels wrong to me - could be class attr, global const
    @property
    def arbitrary_attr(self) -> int:
    return 5

    # use as a getter of protected attrs
    @property
    def a(self) -> str:
    return self._a

    # setter dependant on getter - also makes perfect sense to me
    @a.setter
    def a.setter(self, value: str) -> None:
    self._a = value


    Any thoughts or links to relevant documentation? This is the best I can find: https://kb.novaordis.com/index.php/Python_Language_OOP_Attributes_and_Properties#:~:text=to%20Use%20Properties.-,When%20to%20Use%20Attributes%20and%20When%20to%20Use%20Properties,is%20retrieved%2C%20set%20or%20deleted.

    Continue reading...

Compartilhe esta Página