0

I am fairly new to object oriented programming and I am learning neural networks with pytorch.

I have seen some examples where the class in python will inherit from itself (sub and super class will have the same name). Can someone please explain to me how does it work? I have put a small code as an example below.

import torch.nn as nn 


class LR(nn.module):
  def __init__(self, in_size, out_size):
    super(LR, self).__init__()
    self.linear = nn.Linear(in_size, out_size)

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

I am auditing a pytorch course on coursera. The example is from the course. Here I am confused with the line super(LR, self)

  • 3
    See here: https://stackoverflow.com/questions/222877/what-does-super-do-in-python-difference-between-super-init-and-expl In short however, its just an older syntax. The call is to the parent class constructor. – topsail Jan 16 '23 at 21:35
  • Does this answer your question? [What does 'super' do in Python? - difference between super().\_\_init\_\_() and explicit superclass \_\_init\_\_()](https://stackoverflow.com/questions/222877/what-does-super-do-in-python-difference-between-super-init-and-expl) – STerliakov Jan 16 '23 at 21:41

1 Answers1

1

You might be mistaken in your assumption that you're seeing classes inherit from themselves. In the example you've posted LR inherits from nn.module, and super(LR, self).__init__() will be calling nn.module's __init__ method.

101
  • 8,514
  • 6
  • 43
  • 69
  • 1
    Then will it be the same as writing ``` super().__init__()``` ? Because that is how I am used to doing the inheritance. – programmer_04_03 Jan 16 '23 at 21:49
  • Yes, that's right. Newer versions of Python support the syntax you mentioned here, whereas the syntax in your question is an older style syntax. – 101 Jan 16 '23 at 21:54