Understanding Python super() with __init__() methods

The super() function is a way to refer to the parent class and its attributes. It can be called in a method defined in a subclass to call a method defined in the superclass.

For example, consider the following code:

class Base:
    def __init__(self, value):
        self.value = value

class Derived(Base):
    def __init__(self, value, extra_value):
        self.extra_value = extra_value
        super().__init__(value)

Watch a course Python - The Practical Guide

Here, the Derived class has an __init__ method that takes two arguments: value and extra_value. This method sets the extra_value attribute and then calls the __init__ method of the Base class using super().__init__(value), passing the value argument to it. This is useful because it allows the Derived class to initialize its own attributes and then call the __init__ method of the base class to initialize the attributes of the base class.

By calling the __init__ method of the base class, you can ensure that the base class is properly initialized, which can be important if the base class has important methods or attributes that the subclass relies on.