ruk·si

🐍 Python
Properties

Updated at 2018-06-10 23:39

Properties are created with the @property decorator. Used to manipulate, protect or validate the incoming values to be assigned to attributes.

class Product:
    _name: str

    def __init__(self, name: str) -> None:
        self.name = name

    @property
    def name(self) -> str:
        return self._name

    @name.setter
    def name(self, value: str) -> None:
        self._name = value

lighter = Product('Lighter')
assert lighter.name == 'Lighter'

Classic property syntax is rarely used. There is nothing wrong with it, it is just not a nice to read as the decorator syntax.

class Product:
    _name: str

    def __init__(self, name: str) -> None:
        self.name = name

    def _get_name(self) -> str:
        return self._name

    def _set_name(self, value: str) -> None:
        self._name = value

    name = property(_get_name, _set_name)

lollipop = Product('Lollipop')
assert lollipop.name == 'Lollipop'

Sources

  • Fluent Python, Luciano Ramalho