Function Decorator in Python is a powerful tool that behaves as a normal Python function and enhances the existing functionalities of an object without modifying its structure. In simpler words, Decorators are useful to perform some additional processing(compute) to the existing function.
Generally, a decorator function in Python accepts a function as parameter and returns a function after some modification.
Let’s see a sample decorator function :
def decorator(func1):
Program : To illustrate the working of Decorators
# decorator function
def decorator(func):
# inner function of decorator to implement required logic
def inner():
num = func()
return num**2
# returning the function
return inner
# normal function
def func():
return 10
# calling our decorator function with func() as parameter
final_res = decorator(func)
print(final_res())
O/P : 100
In the above code, we have one decorator function with an inner function to compute the square of the number.
Here, normal function func() is passed as a parameter to our decorator() function during invocation. This decorator() function returns the inner() function. Also, final_res indicates the resultant function.
Using @ symbol for Decorator
To apply decorator to any function, we can use @ symbol along with the decorator name just above the function definition. Consider the above case again, to apply decorator() function to func(), we can write @decoration function above the function definition :
@decoration
def func():
return 10
This means that decoration() function is applied to modify or decorate the result of the func() function. In such cases, where we attach decorator to function using ‘@‘ symbol, we don’t need to call the decorator function explicitly.
Program : To illustrate the working of Decorators using @ symbol.
# decorator function
def decorator(func):
# inner function of decorator to implement required logic
def inner():
num = func()
return num**2
# returning the function
return inner
# normal function
@decorator
def func():
return 10
# calling our func()
final_res = func()
print(final_res)
O/P 100
@decorator means that decoration() function is applied to modify or decorate the result of the func() function. In such cases, we don’t need to call the decorator function explicitly.
Some of the built-in decorators in Python are : @property, @classmethod, and @staticmethod decorators
