Data Model
Callable Objects
Source
class Multiplier:
def __init__(self, factor):
self.factor = factor
self.calls = 0
double = Multiplier(2)
print(double.factor)Output
2__call__ makes the instance usable with function-call syntax.
Source
class Multiplier:
def __init__(self, factor):
self.factor = factor
self.calls = 0
def __call__(self, value):
self.calls += 1
return value * self.factor
double = Multiplier(2)
print(double(5))
print(double(7))Output
10
14Because the callable is still an object, it can remember state across calls.
Source
print(double.calls)Output
2Notes
callable(obj)checks whether an object can be called.- Callable objects are good for named, stateful behavior.
- Prefer plain functions when no instance state is needed.
See also
- prerequisite: Functions
- prerequisite: Closures
- next depth: Callable Types
- related: Bound and Unbound Methods
Run the complete example
Expected output
10
14
2
Execution time appears here after you run the example.