I understand that in python user-defined objects can be made callable by defining a __call__() method in the class definition. For example,
class MyClass:
def __init__(self):
pass
def __call__(self, input1):
self.my_function(input1)
def my_function(self, input1):
print(f"MyClass - print {input1}")
my_obj = MyClass()
# same as calling my_obj.my_function("haha")
my_obj("haha") # prints "MyClass - print haha"
I was looking at how pytorch makes the forward() method of a nn.Module object be called implicitly when the object is called and saw some syntax I didn't understand.
In the line that supposedly defines the __call__ method the syntax used is,
__call__ : Callable[..., Any] = _call_impl
This seemed like a combination of an annotation (keyword Callable[ following : ignored by python) and a value of _call_impl which we want to be called when __call__ is invoked, and my guess is that this is a shorthand for,
def __call__(self, *args, **kwargs):
return self._call_impl(*args, **kwargs)
but wanted to understand clearly how this method of defining functions worked.
My question is: When would we want to use such a definition of callable attributes of a class instead of the usual def myfunc(self, *args, **kwargs)