parentclass中使用super是什么意思?

What is the meaning of using super in the parent class?

正在研究Fast Depth的代码,想知道class的__init__方法这样写是什么意思:

class MobileNet(nn.Module):
    def __init__(self, decoder, output_size, in_channels=3, pretrained=True):

        super(MobileNet, self).__init__()

或这个(始终相同)

class MobileNetSkipAdd(nn.Module):
    def __init__(self, output_size, pretrained=True):

        super(MobileNetSkipAdd, self).__init__()

我不明白super()函数的用法,这里调用的是class本身。

super 有两个参数:

  1. 在 MRO 中用作属性查找起点的 class
  2. 提供 MRO 并最终用于查找属性的对象。

您实际上总是想要使用super静态出现的class,以及当前方法默认接收的对象。因此,在 Python 3 中,编译器更改为自动确定这两个值,允许您简单地编写 super().__init__ 而不是显式提供参数。

请注意,它不像定义默认参数值那么简单,例如

def super(x=..., y=...):

因为“默认值”只能在调用 super 的上下文中确定,而不是您在定义 super 时知道的内容。这就是为什么它需要特殊的编译器支持。

super 函数为您提供父级 class,在您的示例中 nn.Module。请注意,由于 Python 3 你可以说:

super().__init__()

当与 __init__ 一起使用时,它允许您在您正在创建的实例上执行在父级中定义的初始化代码。它后面通常跟有特定于此 subclass.

的初始化代码

由于 MobileNet subclass 是 nn.Module 种类 ,因此更一般的 nn.Module 的特例如果愿意,先执行一般初始化,然后再执行特定初始化是有意义的。