Kodeclik Blog

The Python __call__ method

Let us consider a simple class to store information about restaurants:
Note that we have defined the __init__ method for this class that denotes what needs to happen when we create new objects of the Restaurant class. In this case, the __init__ method takes two arguments (name and address) and these arguments are used to assign respective attributes of the Restaurant object.
We can instantiate a new Restaurant object as follows:
Let us expand our class definition to also include a review component:
Let us agree for the review to be a list of strings, each string denoting one review. We must also correspondingly update our Restaurant object. In the below, we initialize the object to have no reviews at the outset.
Let us now add a add_review method.
Now if we add the following two lines:
We will get the following lines as output:

Using the Python __call__ method

The __call__ method essentially allows you to use objects as functions. To see how, we will update the class definition as follows:
Note that the contents of the __call__ method is exactly the same as the add_review method. However the way we invoke this method, i.e., the way we use it, is syntactically much simpler:
We are essentially using the object (not the class) as a function and passing the review string to it as its argument. The output is still the same:
So what have we learnt? If you have a __call__ method defined using our class, you can invoke the method using either the syntax “object.__call()” or “object()”.
Now, obviously this idea of calling the object as a function will work only if a corresponding __call__ method is defined inside the class definition. You can verify if this will work by using the “callable()” predicate:
This will output:
Try removing the __call__ function and now callable() will return False. In fact, if you attempt to use it as a callable, you will get the error:
The __call__ method is very useful when we are creating APIs and would like to use object oriented programming style in the creation and invocation of the API functions. Note that the arguments to the __call__ method can be anything you would like, so a lot of domain-specific functionality could be embedded inside this method.
If you liked learning about the __call__ method, checkout the Python hasattr() function. Also for more about Python's object-oriented programming features, see our blogpost on private methods in Python.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2023. All rights reserved.