I know that __call__
method in a class is triggered when the instance of a class is called. However, I have no idea when I can use this special method, because one can simply create a new method and perform the same operation done in __call__
method and instead of calling the instance, you can call the method.
I would really appreciate it if someone gives me a practical usage of this special method.
Best Answer
This example uses memoization, basically storing values in a table (dictionary in this case) so you can look them up later instead of recalculating them.
Here we use a simple class with a
__call__
method to calculate factorials (through a callable object) instead of a factorial function that contains a static variable (as that's not possible in Python).Now you have a
fact
object which is callable, just like every other function. For exampleAnd it is also stateful.