【问题标题】:Why do we use super() in a python class? [duplicate]为什么我们在 python 类中使用 super()? [复制]
【发布时间】:2020-03-25 05:12:43
【问题描述】:

我遇到了一个像下面这样的例子,

class Model(tf.keras.Model):
    def __init__(self, vocab_size, embedding_dim, dim, batch_sz):
        super(Model, self).__init__()
        self.dim = dim
        self.embedding = Embedding(vocab_size, embedding_dim)
        self.lstm = LSTM(self.enc_units,
                         recurrent_initializer='glorot_uniform')

在这为什么我们使用super(Encoder, self).__init__()?。我对python的面向对象编程不是很熟悉。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    由于您是从另一个类 class Model(tf.keras.Model): 继承而来,因此在某些情况下,父类或 超类 也必须初始化。由于您有两个 __init__ 函数来知道您正在访问哪个函数,因此 super 用于表示使用父类 __init__ 方法。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-08
    • 2017-02-03
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 2011-09-21
    相关资源
    最近更新 更多