How to Implement __call__ Method in Python: Simple Guide
In Python, you implement
__call__ by defining it inside a class to make its instances callable like functions. When you call an instance, Python runs the __call__ method automatically.Syntax
The __call__ method is defined inside a class with the syntax:
def __call__(self, *args, **kwargs):— this lets the instance accept any arguments.selfrefers to the instance itself.*argsand**kwargsallow passing any number of positional and keyword arguments.
When you call the instance like a function, Python runs this method.
python
class MyCallable: def __call__(self, *args, **kwargs): print("Called with", args, kwargs)
Example
This example shows a class with __call__ that adds two numbers when the instance is called like a function.
python
class Adder: def __init__(self, base): self.base = base def __call__(self, x): return self.base + x add_five = Adder(5) result = add_five(10) print(result)
Output
15
Common Pitfalls
Common mistakes when implementing __call__ include:
- Forgetting to include
selfas the first parameter. - Not handling arguments properly, causing errors when calling the instance.
- Using
__call__without a clear purpose, which can confuse code readers.
Always design __call__ to have a clear, simple behavior.
python
class WrongCall: def __call__(self): # Added self print("Oops") # Correct way: class RightCall: def __call__(self): print("Works fine")
Quick Reference
| Concept | Description |
|---|---|
| __call__(self, *args, **kwargs) | Makes instance callable like a function |
| self | Refers to the instance |
| *args | Accepts any positional arguments |
| **kwargs | Accepts any keyword arguments |
| Calling instance | Triggers __call__ method |
Key Takeaways
Define __call__(self, *args, **kwargs) inside a class to make instances callable.
Calling an instance runs its __call__ method automatically.
Always include self as the first parameter in __call__.
Use *args and **kwargs to accept flexible arguments.
Keep __call__ behavior clear to avoid confusion.