200. Python's __call__ Method
1. Basic Example of __call__ Method
__call__ Methodclass Adder:
def __init__(self, x):
self.x = x
def __call__(self, y):
return self.x + y
# Create an instance of Adder
adder = Adder(5)
# Now you can call the instance like a function
result = adder(3) # Equivalent to calling adder.__call__(3)
print(result) # Output: 82. Using __call__ for Function Objects
__call__ for Function Objectsclass Multiply:
def __init__(self, factor):
self.factor = factor
def __call__(self, number):
return number * self.factor
# Create a multiplier instance
times_two = Multiply(2)
# Using the instance as a function
print(times_two(4)) # Output: 8
print(times_two(10)) # Output: 203. Customizable Behaviors with __call__
__call__4. Using __call__ to Cache Results
__call__ to Cache Results5. Using __call__ for Function Arguments
__call__ for Function Arguments6. Using __call__ with Keyword Arguments
__call__ with Keyword Arguments7. Callable Class Instances for Deferred Execution
8. Using __call__ for Function Composition
__call__ for Function Composition9. __call__ in Class Inheritance
__call__ in Class Inheritance10. Chaining Callable Instances
Conclusion
Last updated