关于Python中super()函数参数及__init__查找位置的技术咨询
super() in Your PyTorch Network Class Let’s walk through your questions about the super() call in your Net class, using your code as a reference:
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
1. Why does super have arguments here?
The super(Net, self) syntax is an explicit way to call the parent class's methods in Python. Here, it’s telling Python: "Look up the target method (__init__ in this case) starting from the parent class of Net, using self as the instance context."
This was the standard approach in Python 2, and many developers still use it in Python 3 for clarity—especially in codebases that might need backward compatibility. It removes any ambiguity about which class’s parent you’re targeting.
2. Can the argument-less super() achieve the same result here?
Absolutely! In Python 3, the argument-less super() is a syntax sugar that automatically infers the current class (Net) and instance (self) from the surrounding context. Replacing super(Net, self).__init__() with super().__init__() will work exactly the same way in your single-inheritance scenario—it just makes the code cleaner and shorter.
3. Where does super() look for the __init__() method?
super() uses the Method Resolution Order (MRO) of your class to find the correct parent method. For your Net class, the MRO is [Net, torch.nn.Module, object] (you can verify this by running print(Net.__mro__)).
When you call super(Net, self).__init__(), Python skips the Net class itself and looks for __init__ in the next class in the MRO list: torch.nn.Module. Since Module has its own __init__ method (which handles critical setup like parameter tracking, device management, and hook registration for PyTorch networks), this is exactly what you need—running that parent initialization ensures your network functions properly (e.g., moving layers to GPU, saving/loading models, etc.).
If torch.nn.Module didn’t define an __init__, Python would keep checking the next class in the MRO, which is object (the base class for all Python objects).
内容的提问来源于stack exchange,提问作者Joemoor94

