Python __call__() Method
The __call__() Method
The __call__() method lets an object be called like a function, using object() syntax.
Example
Create a ClickCounter object that can be called like a function, to count clicks on a button:
class ClickCounter:
def __init__(self):
self.clicks = 0
def __call__(self):
self.clicks += 1
return self.clicks
button_clicks = ClickCounter()
print(button_clicks())
print(button_clicks())
print(button_clicks())
Try it Yourself »
Note: button_clicks is an object, not a function - but __call__() lets you use it with the same () syntax as a function.
Unlike a regular function, it remembers its own state between calls, so the count keeps going up each time it is called.