Home > Blockchain >  why super always need to be called in the __init__
why super always need to be called in the __init__

Time:02-05

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.

CodePudding user response:

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/

  •  Tags:  
  • Related