Python Reference ยท Classes and Special Methods
__call__()
Reference for Python __call__(): make instances callable like functions, keep state between calls, build decorators and use callable() to test.
When a class defines __call__(), its instances can be called like functions: obj(1, 2) runs type(obj).__call__(obj, 1, 2). This lets you combine function-style usage with state that lives on the object.
Callable objects are useful for configurable functions, counters and caches, stateful decorators, and strategy objects that must look like plain functions to the code using them.
class Adder: def __init__(self, n): self.n = n def __call__(self, x): return x + self.n add5 = Adder(5) print(add5(10)) # 15
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
class C: def __call__(self, *args, **kwargs): ... obj = C() obj(1, 2, key=3) # same as C.__call__(obj, 1, 2, key=3)
| Part | Description |
|---|---|
self |
The instance being called. |
*args, **kwargs |
Whatever the caller passes. Any signature is allowed. |
Return value: whatever __call__() returns.
Raises: TypeError: 'X' object is not callable if the class has no __call__().
Usage notes
- Looked up on the type. Python uses
type(obj).__call__, so assigningobj.__call__ = ...on one instance does not make it callable (shown above). - Classes are callable too.
Counter()works because the metaclasstypedefines__call__(), which runs__new__()and__init__(). callable(obj)returnsTruefor functions, methods, classes and instances with__call__(). It cannot promise that a particular call will succeed.- State lives on the instance. That is the main advantage over a plain function, which would need a closure or a global.
- Class-based decorators use
__call__()as the wrapper. Usefunctools.update_wrapper(self, func)to copy the name and docstring. Such decorators do not bind as methods automatically unless you also implement__get__(). - Alternatives. A closure (
def make_adder(n): return lambda x: x + n) orfunctools.partialis lighter when no extra methods are needed. - Keep the signature meaningful. Avoid
__call__(self, *args, **kwargs)unless forwarding; explicit parameters document the interface. - Async.
async def __call__makesawait obj()work.