W3docs

How does the @property decorator work in Python?

In Python, the @property decorator is used to define a method as a "getter" for a class property.

In Python, the @property decorator is used to define a method as a "getter" for a class property. The method is called as if it were an attribute, rather than being called as a method (with parentheses). For example:

Make a setter method in Python using the @property decorator

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

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

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

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

In this example, the x method is decorated with @property, so it acts as a getter for the x property. To define a "setter" method for the property, the @x.setter decorator is used to indicate that the following method is the setter for the x property. This way, you can use the attribute notation for both getting and setting the value.

Test the getter and setter

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

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

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

a = MyClass()
a.x = 10 
print(a.x)

You can also use the @x.deleter decorator to define the behavior for the del statement on the property:

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

    @property
    def x(self):
        return self._x

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

    @x.deleter
    def x(self):
        print("Deleting x")
        self._x = None

a = MyClass()
a.x = 10
del a.x