What is 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:

In Python, a decorator is a special type of function that can modify the behavior of another function without changing its source code. The @ symbol is used to indicate that a function is being used as a decorator.

One specific type of decorator in Python is the call() decorator. This decorator allows you to turn any object into a callable function. A callable function is any object that can be called like a function, i.e., it can be invoked with parentheses.

The call() decorator works by defining a __call__() method on an object. When the object is called as a function, the __call__() method is invoked with the arguments passed to the function call.

Here's an example of how to use the call() decorator: 

 

class MyClass:
    def __init__(self, name):
        self.name = name

    @call
    def __call__(self, *args, **kwargs):
        print(f"{self.name} was called with args: {args}, kwargs: {kwargs}")

obj = MyClass("My Object")
obj(1, 2, 3, a=4, b=5)

In this example, the MyClass object is decorated with the call() decorator. When the obj object is called with arguments, the __call__() method is invoked and prints out the arguments passed to the function call.

Output: My Object was called with args: (1, 2, 3), kwargs: {'a': 4, 'b': 5}'

Submit Your Programming Assignment Details