Python Decorators are important features of the language that allow a programmer to modify the behavior of a class. These features are added functionally to the existing code. This is a type of metaprogramming when the program is modified at compile time. The decorators can be used to inject modified code in functions or classes. The decorators allow the program to be modified to add any code that has a special role to play. Decorators are called before the definition of the function you have decorated.
The use of decorators could be explained with the following example. Suppose we write a program to “Decorate” a function using another function. the code goes like:
This is my function. The function was decorated. This is my function.
Firstly, “This is my function” appears because of the function call my_function(). The second set of output was because of the Decorating function.
The same thing can also be done by using decorators. The following code explains that. Note that the decorating statement is defined above the function to be decorated.
The function was decorated. This is my function.
The call() decorator
The call() decorator is used in place of the helper functions. In python, or in any other languages, we use helper functions for three major motives:
- To identify the purpose of the method.
- The helper function is removed as soon as its job is completed. And
- The purpose of helper function matches with that of decorator function.
The following example will illustrate the significance of the call decorator method. In this example, we would be building a list of the doubles of the first “n” numbers, using a helper function.
The code is as follows:
The above code could also be written using the call() decorator:
As it is observed, that the output is same as before, this means that the call() decorator works almost exactly like helper functions.
- Is Python call by reference or call by value
- Class as decorator in python
- Data Classes in Python | Set 2 (Decorator Parameters)
- Decorator Method - Python Design Patterns
- How to Call a C function in Python
- Python: Call Parent class method
- Context Manager Using @contextmanager Decorator
- Python - Call function from another function
- How to remove error Call to undefined function curl_init()?
- How to call some function before main() function in C++?
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Index of Non-Zero elements in Python list
- Python | Convert list to Python array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.