简体   繁体   中英

Usage of "__call__(self,x): return self.foo_method(x)" and its difference to "class.foo_method(x)"

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 eg 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM