首页 > 解决方案 > 在父类本身中使用了“super()”,为什么?

问题描述

我是 python 编程的新手,对 python 中的 oops 概念感到困惑。我知道super()是用来使用父类中定义的方法,但是我不明白为什么父类本身使用super()关键字。

class BahdanauAttention(tf.keras.Model):
  def __init__(self, units):
    super(BahdanauAttention, self).__init__()
    self.W1 = tf.keras.layers.Dense(units)
    self.W2 = tf.keras.layers.Dense(units)
    self.V = tf.keras.layers.Dense(1)

标签: pythonoopinheritance

解决方案


BahdanauAttention继承自tf.keras.Model,意味着其内部的调用super实际上init调用了 的init方法tf.keras.Model

还有一件事:从 Python 3 开始,您不需要将任何参数传递给super调用:

super().__init__()

推荐阅读