call() decorator in Python
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.