为什么不是 Pytorch 中的 super().__init__(Model,self)

Sus*_*usy 2 python oop inheritance class pytorch

对于 torch.nn.Module()

根据官方文档:所有神经网络模块的基类。你的模型也应该继承这个类。模块还可以包含其他模块,允许将它们嵌套在树结构中。您可以将子模块分配为常规属性。

import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))
Run Code Online (Sandbox Code Playgroud)

它使用super(Model, self).__init__() 为什么不super().__init__(Model, self)

kma*_*o23 5

这个构造:

super().__init__(self)
Run Code Online (Sandbox Code Playgroud)

仅在 Python 3.x 中有效,而以下构造,

super(Model, self).__init__()
Run Code Online (Sandbox Code Playgroud)

适用于 Python 2.x 和 Python 3.x。因此,PyTorch 开发人员不想通过强制执行Python 3.x 语法super()来破坏用 Python 2.x 编写的所有代码,因为在这种情况下,这两种构造本质上都在做相同的事情,即初始化以下变量:

    self.training = True
    self._parameters = OrderedDict()
    self._buffers = OrderedDict()
    self._backward_hooks = OrderedDict()
    self._forward_hooks = OrderedDict()
    self._forward_pre_hooks = OrderedDict()
    self._state_dict_hooks = OrderedDict()
    self._load_state_dict_pre_hooks = OrderedDict()
    self._modules = OrderedDict()
Run Code Online (Sandbox Code Playgroud)

详情参见 PyTorch 论坛中关于该主题的相关讨论,is-there-a-reason-why-people-use-super-class-self-init-instead-of-super-init?