Here is how to use the super() with __init__() methods in Python.


class MyParentClass:
    def __init__(self, arg1, arg2):
        # Do something with arg1 and arg2

class MyChildClass(MyParentClass):
    def __init__(self, child_arg, arg1, arg2):
        # Initialize the parent class with arg1 and arg2
        super().__init__(arg1, arg2)
        # Do something with child_arg 

Output

 


Explanation

The super() function is used to call a method from the parent class. It is often used in the __init__() method to initialize the parent class with the correct arguments.

In this example, MyChildClass is a child class of MyParentClass. When we call MyChildClass.__init__(), we use the super() function to initialize the parent class with arg1 and arg2. This ensures that the parent class is properly initialized before we do anything else in the __init__() method of MyChildClass.

The super() function is a convenient way to call a method in the parent class without having to explicitly specify the parent class name. This can make your code more readable and maintainable. It is particularly useful when dealing with complex class hierarchies.

Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.


Subscribe to be the first to know when a new Python course is released.