小编chm*_*777的帖子

为什么 PyTorch 自定义模块中需要超级构造函数?

为什么super(LR, self).__init__()需要在下面的代码中调用?否则我会收到错误“AttributeError: cannot assign module before Module.init () call”。该错误是由self.linear = nn.Linear(input_size, output_size).

我不明白调用super(LR, self).__init__()和能够将 nn.Linear 对象分配给 self.linear之间有什么联系。nn.Linear 是一个单独的对象,它可以分配给任何类之外的变量,那么为什么super(LR, self).__init__()需要调用将 Linear 对象分配给类内的 self.linear 呢?

class LR(nn.Module):
    
    # Constructor
    def __init__(self, input_size, output_size):
        
        # Inherit from parent
        super(LR, self).__init__()
        self.test = 1
        self.linear = nn.Linear(input_size, output_size)
        
    
    # Prediction function
    def forward(self, x):
        out = self.linear(x)
        return out
Run Code Online (Sandbox Code Playgroud)

python inheritance super pytorch

5
推荐指数
2
解决办法
1586
查看次数

标签 统计

inheritance ×1

python ×1

pytorch ×1

super ×1