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.
            Asked
            
        
        
            Active
            
        
            Viewed 1,825 times
        
    0
            
            
         
    
    
        Rui
        
- 117
- 2
- 12
- 
                    2If 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" <-- nope. It only needs to be called if you want it to. If for some reason you require the same class but a different __init__ you simply don't call the super for it. Same goes for every method on the class btw. It also ties in with the "explicit over implicit" python idiom. – JustLudo Feb 04 '22 at 11:57
1 Answers
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
        
- 1,020
- 2
- 14
- 14