How to Use the Python __call__() Method

09/18/2021

Contents

In this article, you will learn how to use the Python __call__() method.

Python __call__() Method

The __call__() method in Python allows an object to be called as if it were a function. When you call an object that has a __call__() method defined, Python automatically calls the __call__() method of that object, passing in any arguments that were used in the original call.

Here’s an example of how to use the __call__() method in Python:

class MyClass:
    def __call__(self, x, y):
        return x + y

obj = MyClass()

result = obj(3, 5)  # calling obj as if it were a function
print(result)  # output: 8

In the example above, we define a class MyClass and define a __call__() method for it. This method takes two arguments x and y and returns their sum.

We then create an instance of MyClass and assign it to the variable obj. We can now call obj as if it were a function, passing in two arguments 3 and 5. When we do this, Python automatically calls the __call__() method of obj, passing in 3 and 5 as arguments. The __call__() method then returns their sum, which is 8.

This is just a simple example, but the __call__() method can be used to define much more complex behavior for objects that can be called as functions. For example, you could define a class that generates random numbers when called, or a class that runs a simulation when called with certain parameters.