[Python] How does the @property decorator work in Python?

Discussão em 'Python' iniciado por Stack, Julho 19, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator.

    This example is from the documentation:

    class C:
    def __init__(self):
    self._x = None

    def getx(self):
    return self._x

    def setx(self, value):
    self._x = value

    def delx(self):
    del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")


    property's arguments are getx, setx, delx and a doc string.

    In the code below property is used as a decorator. The object of it is the x function, but in the code above there is no place for an object function in the arguments.

    class C:
    def __init__(self):
    self._x = None

    @property
    def x(self):
    """I'm the 'x' property."""
    return self._x

    @x.setter
    def x(self, value):
    self._x = value

    @x.deleter
    def x(self):
    del self._x


    How are the x.setter and x.deleter decorators created in this case?

    Continue reading...

Compartilhe esta Página