Super(model) in init

class LinearRegressionModel(nn.Module):
   def __init__(self, input_dim, output_dim):
      super(LinearRegressionModel, self).__init__()
      self.linear = nn.Linear(input_dim, output_dim)

   def forward(self, x):
      out = self.linear(x)
      return out

Can any of you please explain the use of the statement:

super(LinearRegressionModel, self).__init__()

Thanks!

1 Like

The super call delegates the function call to the parent class, which is nn.Module in your case.
This is needed to initialize the nn.Module properly. Have a look at the Python docs for more information.

4 Likes

Here is a link to learn more about ‘Super’ => https://realpython.com/python-super/

Based on reading the link @KarthikR provided, it seems to me that in the context of the original code, in Python 3 the original super statement is completely equivalent to just:

super().__init__()

(and per the recommendations at that link, this simpler version is in fact preferred).

Can anyone confirm that this is correct?

1 Like

I think you are right. More information ref to Martijn Pieters

The reason to use super is so that child classes that may be using cooperative multiple inheritance will call the correct next parent class function in the Method Resolution Order (MRO).

In Python 3, we can call it like this:

class ChildB(Base):
    def __init__(self):
        super().__init__()

In Python 2, you were required to call super like this with the defining class’s name and self, but you’ll avoid this from now on because it’s redundant, slower (due to the name lookups), and more verbose (so update your Python if you haven’t already!):

super(ChildB, self).__init__()

Without super, you are limited in your ability to use multiple inheritance because you hard-wire the next parent’s call:

Base.__init__(self) # Avoid this.

2 Likes