0

See the screenshot of the code below. In the code block, it can be seen from the class definition part that the ResNet is a subclass of nn.Module, and when we define the __init__ function, we still call the super().__init__(). I am really confused about that, I have already look a stack overflow explanation but the accept answer is too brief so I don't get it (for example, if super().__init__() always need to be called why python don't just integrate it inside the __init__()), I was hoping a more easy to understand explanation with some examples.

Rui
  • 105
  • 7
  • 2
    If you want to run the code of the parent classes' `__init__`, then you call `super().__init__`. If you do not want to run the code of the parent classes' `__init__`, then you do not call `super().__init__`. – timgeb Feb 04 '22 at 10:44
  • 1
    "always need to be called" – JustLudo Feb 04 '22 at 11:57

1 Answers1

0

The Python super() method lets you access methods from a parent class from within a child class. In other words this will work only if you are working in a child class inherited from another. This helps reduce repetition in your code. super() does not accept any arguments.

class Parent():
  def __init__(self, name):
    self.hair = 'blonde'
    self.full_name = name + ' kurt'

class Child(Parent):
  def __init__(self, brand):
    super().__init__('franz')
    print(self.fullname) # franz kurt

    # inherited blonde but the phenotype of the hair in child is different 
    # so the attribute was overwrited
    self.hair = 'dark hair' 

One core feature of object-oriented programming languages like Python is inheritance. Inheritance is when a new class uses code from another class to create the new class.

When you’re inheriting classes, you may want to gain access to methods from a parent class. That’s where the super() function comes in.

Reference: https://realpython.com/python-super/

Franz Kurt
  • 645
  • 2
  • 10
  • 11