Summary: In this tutorial, we will learn what is __call__ in Python, what does it do, and when we should use it in our Python programs.

What is __call__ in Python?

__call__ is a special function in Python that, when implemented inside a class, gives its instances (objects) the ability to behave like a function.

It means after implementing __call__ method inside the Python class, we can invoke its instances like a function.

Example 1:

class Student():
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
        
    def __call__(self):
        print(f"Name: {self.name}, Roll: {self.roll}")
        
#creating an instance of the Student class        
stud1 = Student("Newton", "007")

#Using the instance like a function
stud1()

Output:

Name: Newton, Roll: 007

As you can see, the stud1() is calling the __call__ method of the instance. This means we can even pass arguments like normal functions.

Example 2:

class Student():
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
        
    def __call__(self, remarks):
        print(f"Name: {self.name}, Roll: {self.roll}")
        print(f"Remarks: {remarks}")
        
#creating an instance of the Student class        
stud1 = Student("Newton", "007")

#Using the instance like a funciton
stud1("Good Student")

Output:

Name: Newton, Roll: 007
Remarks: Good Student

How is this happening?

In Python, object() is the shorthand notation for object.__call__().

For example, in the following Python code, instead of function(), we are using the function.__call__() statement to invoke the function and it runs without any error:

def function():
    print("function called")

function.__call__()

Output:

function called

Therefore, when we use the () operator on any object, we are indirectly calling the __call__ method of that particular object.

It is important to note that functions in Python are also objects.

When should we use __call__ in Python?

When we want the instances of a class to behave like a function, we should implement the __call__ method.

Since the __call__ method makes instance callable, we can use it as a decorator.

Example:

class Cloud:
    def __init__(self, func):
        self.func = func
        
    def __call__(self):
        print("Connected to cloud")
        self.func()
        print("Connection to cloud Closed")

@Cloud
def upload_file():
    print("Uploading File....")
    
upload_file()

Output:

Connected to cloud
Uploading File….
Connection to cloud Closed

Conclusion

The __call__ is a reserved method in Python that makes the instances of a class callable.

We should implement __call__ inside the class, if we want its instances to behave like functions.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply