How to make class object callable

Posted by Afsal on 09-Dec-2022

Hi Pythonistas!

Today we will learn how to make the class object callable like the function. In python an object is callable if it has a magic method __call__ is written. Every python function has this method by default. If we write this magic method we can make the class callable. Let us check with an example

Code

class OrdinaryClass:
    pass

a = OrdinaryClass()
a()

Output

Traceback (most recent call last):
  File "callable_class.py", line 7, in <module>
a()
TypeError: 'OrdinaryClass' object is not callable

Here there is no callable function for the class. Hence it will raise an error if we try to call the class object.

Now we can make a callable class

Code

class CallableClass:
    def __call__(self):
        print("I am callable")

a = CallableClass()
a()

Output

I am callable

To check if an instance is callable the is a built-in function callable. This return Boolean based on the object passed

Code

print("Is ordinary class object callable: ", callable(OrdinaryClass()))

print("Is callable class object callable: ", callable(CallableClass()))

Output

Is ordinary class object callable:  False

Is callable class object callable:  True

Hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in