Make an instance callable like a function by defining __call__().
How It Works
__call__(self, ...) enables syntax such as instance(value). Callable objects can retain configuration or state between calls, making them useful as strategies, validators, and callbacks.
callable(instance) is True when its type supports a call operation.
Step-by-Step Example
class PrefixFormatter:
def __init__(self, prefix):
self.prefix = prefix
def __call__(self, message):
return f"{self.prefix}: {message}"
formatter = PrefixFormatter("INFO")
print(formatter("Job finished"))
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
INFO: Job finished
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Build a callable formatter with a suffix instead of a prefix.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Expecting a class instance to be callable automatically without __call__().
- Confusing a configured callable object with a stateless function when state changes matter.
Key Takeaways
- Make an instance callable like a function by defining __call__().
- __call__(self, ...) enables syntax such as instance(value).
- callable(instance) is True when its type supports a call operation.