How To Use __Call__ In Python

In this tutorial, we will discuss the powerful but less-known concept of call in Python. We will understand the basics of call and see how to use it in a Python class. By the end of this tutorial, you will have a solid understanding of call and how to leverage it to write cleaner, more efficient code.

Understanding __call__

The call method is a built-in function in Python that allows you to implement a custom behavior when an instance of a class is “called” like a function. This is achieved by defining a method named call within the class. When an object is called, the call method is executed automatically.

Defining __call__ in a Python Class

To implement the call method in a Python class, follow these steps:

  1. Define your class.
  2. Define your init method (optional).
  3. Define the call method within your class and add the logic you want to execute when the object is called as a function.

Here’s an example class with a call method defined:

In the example above, when an object of Greeting is called as a function, the custom call method we defined will be executed.

Using __call__

Now that we have defined a class with our custom call method, let’s see how to use it:

  1. Instantiate the class.
  2. Call the object as you would call a normal function.

Here’s an example with the Greeting class defined earlier:

In the example above, we instantiate the Greeting class with our greeting text and then call the instantiated object as a function with the name parameter. The call method in the class is then automatically executed, yielding the desired output.

Full Example Code

Output

Hello, John Doe!

Conclusion

In this tutorial, we learned about the call method in Python and how to use it in a class to enable calling the object as a function. With the call method, you can write cleaner code that is more enjoyable to work with. So go ahead, experiment with call in your Python classes, and take your programming skills to the next level.