Stateful callable
A configured operation needs to be reused with function-call syntax while retaining instance attributes.
Python · Module
Defining __call__ on a class makes its instances callable like functions. Calling an instance dispatches to the class’s __call__ method with the instance and supplied arguments.
Define __call__ on a class to give its instances function-like invocation. When an instance x is called with arguments, Python dispatches to the class’s __call__ implementation with x as the first argument, so the method can use instance state and return the call result.
object.__call__(self [, args...])| Name | Type | Description |
|---|---|---|
self | object | The instance that receives the call. |
args | tuple | Optional positional arguments supplied by the caller. |
The value returned by the class's __call__ implementation; the documentation does not prescribe a particular return type.
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, value):
return self.factor * value
double = Multiplier(2)
print(double(5)) # 10The instance can be invoked with function-call syntax because its class defines __call__.
A configured operation needs to be reused with function-call syntax while retaining instance attributes.
An object should present a simple operation interface to APIs that accept callable objects.
A class should model a reusable transformation whose configuration is supplied at construction time.
Defining __call__ makes instances of a class callable. Calling x(arg1, arg2) dispatches approximately to type(x).__call__(x, arg1, arg2).
Follow-up: How can you check this property at runtime? Use callable(x), which tests whether the object can be used with call syntax.
The first parameter is self, representing the instance being called. Additional positional arguments are conventionally captured by *args, as shown by the documented object.__call__(*self [, *args...*]) form.
Follow-up: How would keyword arguments be supported? Define the method with **kwargs, or with explicit keyword parameters, according to the desired interface.
A callable instance can retain configuration in attributes and apply that state whenever it is invoked. This provides function-like use while keeping object state and behavior together.
Follow-up: What does the documentation say about object.__call__ itself? The object class has no implementation; the behavior comes from the class defining or inheriting the method.
callable()objecttypeCallsuser-defined classes