Python’s Function Decorators, Part 1 of a Set (Introduction) Read and Discuss Topics Presented in Courses and Videos Background
The following is a list of essential information about Python functions that is necessary to comprehend decorator.
functions.
- In Python, we can define a function inside another function.
- In Python, a function can be passed as parameter to another function (a function can also return another function).
- Python
Python
|
Output:
Welcome to GeeksforGeeks
Decorator Function for Functions A function known as a decorator is one that only accepts another function as its input argument and then returns another function. This makes it easier to “wrap” functionality in the same code on several occasions. For instance, the code that was just shown may be rewritten as follows: To define a decorator that will be applied to another function, we use the @func name notation.
function.
- Python
Python
|
Output:
Welcome to GeeksforGeeks
In addition, decorators might be helpful when attaching data to something (or adding an attribute to).
functions.
- Python
Python
|
Output:
5 3
Calling add(2, 3) would simply yield the sum of two integers, but when we use add.data then ‘add’ function is sent into then decorator function ‘attach data’ as argument and this function returns ‘add’ function with an attribute ‘data’ that is set to 3 and thus displays it. Decorators in Python are a strong tool that may eliminate repetition from code. For more information, please refer to the Decorators in Python documentation.