Python __call__()
The __call__()
method in Python is a special method that allows an object to be callable like a function. When the __call__()
method is defined inside a class, instances of that class can be called as if they were functions.
Here is an example to illustrate the usage of __call__()
method:
class Foo:
def __init__(self):
self.counter = 0
def __call__(self):
self.counter += 1
print(f"Instance called {self.counter} times")
foo = Foo()
foo() # This will print: "Instance called 1 times"
foo() # This will print: "Instance called 2 times"
In this example, the Foo
class has a __call__()
method defined. The method increments the counter
attribute each time it is called and prints the value of counter
. Instances of the Foo
class can be called as if they were functions, and each call will increment the counter
attribute and print the updated value.
The __call__()
method can also accept arguments and return a value, just like regular functions.