问题
When writing customized tf.keras layers, we have to implement the "call" method, since a object of a class can be called like a function with "()" only(?) if the object has a valid "__call__" method. while I didn't find something like
class tf.keras.model():
def __call__(self, input):
return self.call(input)
in the keras.model source, how could all this work?
回答1:
from keras.models import Model
import inspect
inspect.getmro(Model)
# (keras.engine.training.Model, keras.engine.network.Network, keras.engine.layer._Layer)
inspect.getmro(CLS) returns a tuple of class CLS's base classes, including CLS, in method resolution order.
The __call__ method inside Model infact comes from keras.engine.layer._Layer class. You can refer the code here
On line 996, inside __call__ method call_fn is assigned as call & is indeed called on line 979.
So, essentially, in a way I guess, the following holds true -
def __call__(self, input):
return self.call(input)
Let's discuss further!
来源:https://stackoverflow.com/questions/63008991/why-implementing-the-call-method-when-subclassing-a-tf-keras-layeror-model-c