Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Python super() function: call the constructor of the parent class

The super() function in Python is used to call a method from the parent class (also known as a superclass). It is often utilized in object-oriented programming when you want to override a method in a derived class (subclass) while still maintaining the functionality of the method from the parent class.

This tutorial will explain the concept and usage of the super() function in Python.

  • Inheritance in Python:

Inheritance is a fundamental concept in object-oriented programming that allows one class to inherit attributes and methods from another class. The class that is being inherited is called the parent class or superclass, and the class that is inheriting is called the child class or subclass.

class Parent:
    pass

class Child(Parent):
    pass
  • Overriding methods:

When a child class has a method with the same name as a method in the parent class, the child class method is said to override the parent class method. This allows you to change or extend the behavior of the parent class method in the child class.

class Parent:
    def greet(self):
        print("Hello from Parent class")

class Child(Parent):
    def greet(self):
        print("Hello from Child class")

c = Child()
c.greet()  # Output: Hello from Child class
  • Using super():

The super() function allows you to call a method from the parent class in the child class. This is useful when you want to extend the functionality of the parent class method without completely overriding it.

class Parent:
    def greet(self):
        print("Hello from Parent class")

class Child(Parent):
    def greet(self):
        super().greet()
        print("Hello from Child class")

c = Child()
c.greet()
# Output:
# Hello from Parent class
# Hello from Child class
  • super() with __init__ method:

A common use case of super() is when initializing a child class. You can use super() to ensure that the parent class's __init__ method is called, initializing the inherited attributes.

class Parent:
    def __init__(self, x):
        self.x = x

class Child(Parent):
    def __init__(self, x, y):
        super().__init__(x)
        self.y = y

c = Child(1, 2)
print(c.x, c.y)  # Output: 1 2
  • Multiple inheritance and Method Resolution Order (MRO):

When a class inherits from multiple parent classes, Python uses the MRO to determine the order in which the parent classes are considered for method calls. The super() function follows the MRO to determine which method to call.

class A:
    def greet(self):
        print("Hello from class A")

class B:
    def greet(self):
        print("Hello from class B")

class C(A, B):
    def greet(self):
        super().greet()

c = C()
c.greet()  # Output: Hello from class A

In this example, the MRO for class C is [C, A, B], so when calling super().greet() in class C, it calls the greet() method from class A.

In conclusion, the super() function in Python is a powerful tool for working with inheritance, method overriding, and multiple inheritance. It enables you to call parent class methods while preserving the intended behavior of your derived classes.

  1. How to use super() to call the parent class constructor:

    • Description: super() is used to call the constructor of the parent class. It ensures that the parent class is properly initialized before the child class.
    • Code:
      class ParentClass:
          def __init__(self, value):
              self.value = value
      
      class ChildClass(ParentClass):
          def __init__(self, value, child_value):
              super().__init__(value)
              self.child_value = child_value
      
      # Using super() to call the parent class constructor
      child_obj = ChildClass(42, "Hello")
      print(child_obj.value)        # Output: 42
      print(child_obj.child_value)  # Output: Hello
      
  2. Passing arguments with super() in Python constructors:

    • Description: Arguments can be passed to the parent class constructor using super(), allowing for the initialization of shared attributes.
    • Code:
      class ParentClass:
          def __init__(self, value):
              self.value = value
      
      class ChildClass(ParentClass):
          def __init__(self, value, child_value):
              super().__init__(value)
              self.child_value = child_value
      
      # Passing arguments with super() in Python constructors
      child_obj = ChildClass(42, "Hello")
      print(child_obj.value)        # Output: 42
      print(child_obj.child_value)  # Output: Hello
      
  3. super() in single and multiple inheritance scenarios:

    • Description: super() works seamlessly in both single and multiple inheritance scenarios, ensuring proper method resolution order (MRO).
    • Code:
      class FirstClass:
          def __init__(self, value):
              self.value = value
      
      class SecondClass(FirstClass):
          def __init__(self, value, second_value):
              super().__init__(value)
              self.second_value = second_value
      
      class ThirdClass(SecondClass):
          def __init__(self, value, second_value, third_value):
              super().__init__(value, second_value)
              self.third_value = third_value
      
      # super() in multiple inheritance
      third_obj = ThirdClass(42, "Hello", True)
      print(third_obj.value)        # Output: 42
      print(third_obj.second_value)  # Output: Hello
      print(third_obj.third_value)   # Output: True
      
  4. Method chaining and super() in Python classes:

    • Description: super() allows method chaining, where a method in a subclass calls the same method in the parent class and adds additional behavior.
    • Code:
      class ParentClass:
          def method(self):
              print("Parent method")
      
      class ChildClass(ParentClass):
          def method(self):
              super().method()
              print("Child method")
      
      # Method chaining and super() in Python classes
      child_obj = ChildClass()
      child_obj.method()