__call__ Makes Instances Callable
A class with __call__ produces instances that work anywhere a function fits, such as sort keys, and callable() reports the capability.
Code
class Multiplier:
def __init__(self, factor):
self.factor = factor
# __call__ lets instances be invoked like functions
def __call__(self, value):
return value * self.factor
double = Multiplier(2)
triple = Multiplier(3)
print(double(10), triple(10))
class LastLetter:
def __call__(self, word):
return word[-1]
# Callable instances drop into any function-shaped slot, like sort keys
words = ["banana", "fig", "cherry"]
print(sorted(words, key=LastLetter()))
# callable() reports the capability, not the type
print(callable(double), callable(Multiplier))Output
Captured from a sandboxed run of this snippet in the build pipeline.
20 30
['banana', 'fig', 'cherry']
True TrueHow it works
Everything happens inside the classes Multiplier and LastLetter and the functions __init__ and __call__.
Caveats
- Nothing to install: the snippet stays inside the standard library.
Putting it to use
The primary signature is def __init__(self, factor)
Core lines under the microscope
def __init__(self, factor):
self.factor = factor
def __call__(self, value):
return value * self.factor
def __call__(self, word):
return word[-1]
Interactive Tools for This Topic
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `__init__`, `__call__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.