How does __call__ let an instance of a class be invoked like a function?
Short answer
Defining __call__(self, *args, **kwargs) makes instances callable with parentheses, e.g., obj(x, y), which Python translates to obj.__call__(x, y).
Advertisement
AModel answer
Defining __call__(self, *args, **kwargs) makes instances callable with parentheses, e.g., obj(x, y), which Python translates to obj.__call__(x, y). This is used for stateful callables like decorators-as-classes, memoized functions, or configurable strategy objects that need to remember state between calls.
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
print(double(5)) # 10 -- called like a functionReal-world example
A machine learning preprocessing pipeline defines transform classes with __call__ so each transform can be applied like a function while still holding configuration state (e.g., normalization parameters).
Likely follow-ups
- How does __call__ enable class-based decorators?
- What's the performance difference vs a plain function?
Related topics