为什么在子classing tf.keras层(或模型)class时实现"call"方法使层(模型)对象可调用?

why implementing the "call" method when subclassing a tf.keras layer(or model) class makes the layer(model) object callable?

编写自定义tf.keras层时,我们必须实现“call”方法,因为class的对象可以像使用“()”的函数一样被调用仅 (?) 如果对象具有有效的“__call__”方法。虽然我没有找到

class tf.keras.model():
def __call__(self, input):
    return self.call(input)

在 keras.model 源代码中,这一切如何工作?

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 class CLS 基础 classes 的元组,包括 CLS,按照方法解析顺序。

Model里面的__call__方法实际上来自keras.engine.layer._Layerclass。可以参考代码here

在线996, inside __call__ method call_fn is assigned as call & is indeed called on line 979.

所以,基本上,在某种程度上,我猜,以下是正确的 -

def __call__(self, input):
    return self.call(input)

让我们进一步讨论!