Junior — Middle
Can you explain the purpose and use of the __call__ method in Python?
sobes.tech AI
Answer from AI
The __call__ method in Python allows an instance of a class to be called as a function. If this method is defined in a class, then the class object can be used with the call syntax obj(), and the code inside __call__ will be executed.
This is convenient for creating objects with behavior similar to functions, but with the ability to maintain state.
Example:
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, value):
return value * self.factor
mul_by_3 = Multiplier(3)
print(mul_by_3(10)) # Outputs 30
In this example, the object mul_by_3 behaves like a function that multiplies the input value by 3.