Home > Back-end >  Usage of "__call__(self,x): return self.foo_method(x)" and its difference to "class.f
Usage of "__call__(self,x): return self.foo_method(x)" and its difference to "class.f

Time:05-18

The code derives from a neural network implementation from scratch in python, you can check full code on this link if you want and down here the critical part concerning my question which is I hope python oriented:

class model:
   def __init__(self,blah blah...):
      blah blah

   def forward(self,x):
      blah blah
      return output_of_neural_network

   def __call__(self,x):
      return forward(x)

Presuming that we want to use the forward method in the following part of our code...

What is the purpose of calling the class as a function e.g. model(xtrain) instead of model.forward(xtrain)?

Are there any functional differences associated with the instance or the variables of the class object when being called as a function instead of applying its method directly?

CodePudding user response:

It is, as you thought, pure syntactic sugar with no functional difference at all.

I guess the reasoning behind this is thinking of your Model as transforming the input data. This, I believe, scikit-learn chooses to do with its transform method, which is arguably less ambiguous.

  • Related