A decorator feature in Python wraps in a function, appends several functionalities to existing code and then returns it. Methods and functions are known to be callable as they can be called. Therefore, a decorator is also a callable that returns callable. This is also known as metaprogramming as at compile time a section of program alters another section of the program. Note: For more information, refer to Decorators in Python
Python @property decorator
@property decorator is a built-in decorator in Python which is helpful in defining the properties effortlessly without manually calling the inbuilt function property(). Which is used to return the property attributes of a class from the stated getter, setter and deleter as parameters. Now, lets see some examples to illustrate the use of @property decorator in Python: Example 1:
Python
class Portal:
def __init__( self ):
self .__name = ''
@property
def name( self ):
return self .__name
@name .setter
def name( self , val):
self .__name = val
@name .deleter
def name( self ):
del self .__name
p = Portal();
p.name = 'GeeksforGeeks'
print (p.name)
del p.name
print (p.name)
|
Output:GeeksforGeeks
## An error is thrown
Traceback (most recent call last):
File "main.py", line 42, in
print (p.name)
File "main.py", line 16, in name
return self.__name
AttributeError: 'Portal' object has no attribute '_Portal__name'
Here, the @property decorator is used to define the property name in the class Portal, that has three methods(getter, setter, and deleter) with similar names i.e, name(), but they have different number of parameters. Where, the method name(self) labeled with @property is a getter method, name(self, val) is a setter method as it is used to set the value of the attribute __name and so its labeled with @name.setter. Lastly, the method labeled with @name.deleter is a deleter method which can delete the assigned value by the setter method. However, deleter is invoked with the help of a keyword del. Example 2:
Python
class Celsius:
def __init__( self , temp = 0 ):
self ._temperature = temp
@property
def temp( self ):
print ("The value of the temperature is : ")
return self ._temperature
@temp .setter
def temp( self , val):
if val < - 273 :
raise ValueError("It is a value error.")
print ("The value of the temperature is set .")
self ._temperature = val
cel = Celsius();
cel.temp = - 270
print (cel.temp)
cel.temp = - 300
print (cel.temp)
|
Output:The value of the temperature is set.
The value of the temperature is:
-270
# An error is thrown
Traceback (most recent call last):
File "main.py", line 47, in
cel.temp = -300
File "main.py", line 28, in temp
raise ValueError("It is a value error.")
ValueError: It is a value error.
Here, a value error is thrown as the value of the temperature assigned must be above -273. But here it is -300. Hence, a value error is thrown.