【问题标题】:Where is this super function looking for __init__()? [closed]这个超级函数在哪里寻找 __init__()? [关闭]
【发布时间】:2020-10-19 12:40:37
【问题描述】:

我正在查看这个 python 类,并试图弄清楚为什么超级函数有任何参数。如果我的理解是正确的,那么在这种情况下,没有参数的 super() 将做同样的工作。我说的对吗?

这是代码

class Net(torch.nn.Module):
    def __init__(self, input_size, hidden_size):
        super(Net, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.fc1 = torch.nn.Linear(self.input_size, self.hidden_size)
        self.relu = torch.nn.ReLU()
        self.fc2 = torch.nn.Linear(self.hidden_size, 1)
        self.sigmoid = torch.nn.Sigmoid()
    
    def forward(self, x):
        hidden = self.fc1(x)
        relu = self.relu(hidden)
        output = self.fc2(relu)
        output = self.sigmoid(output)
        return output

【问题讨论】:

  • 添加一些打印输出,尝试一下,看看会发生什么。

标签: python class object subclass subclassing


【解决方案1】:

在 Python 2 中,参数不是可选的。在 Python 3 中,有一种特殊的编译器魔法可以确定要使用的参数是否被省略。在Net.__init__ 的上下文中,super() 等价于super(Net, self)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-21
    • 2021-03-24
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    相关资源
    最近更新 更多