Python __call__ method
November 18, 2021 by Jane
In Python there are a lot of built-in methods, including the infamous __main__ method. __call__ is another built-in method. The way it works is that it makes it possible to call an object like a function.
We're familiar with this code:
my_obj = Obj() // constructed
However did you know you can do this?
my_obj()
Yes. This is possible if we define the __call__ built-in method.
E.g.
class Obj():
def __init__(self):
print('init called')
def __call__(self):
print('use object as function')
> my_obj = Obj
init called
> my_obj()
use object as function