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:
python
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())
Note:
button_clicksis 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.