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. The method is called as if it were an attribute, rather than being called as a method (with parentheses). For example:
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
Watch a video course
Python - The Practical Guide
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.
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 @property
decorator along with the @x.deleter
decorator to define a __del__
method for the property.