/  Technology   /  Super() work with multiple Inheritance in Python

Super() work with multiple Inheritance in Python

 

Before understanding the super() function, let’s learn something about multiple inheritance.

 

When a class inherits some or all the properties from another class, It’s known as Inheritance. The inherited class is called the subclass and the class from which properties are inherited is the parent class. When one child class can inherit properties from multiple parent classes, it’s called Multiple Inheritance.

 

The super() function allows us to avoid using the base class name explicitly. In Python, the super() function is dynamically called as unlike other languages, Python is a dynamic language. This function can be used both in Single and Multiple Inheritance.

 

Working with Single Inheritance:

Example:

class Father:
   fname = ""
   def father(self):
      print(self.name)

class Mother:
   mname = ""
   def mother(self):
      print(self.name)

class Child(Father, Mother):
   def parents(self):
      print("Father :", self.fname)
      print("Mother :", self.mname)

s1 = Child()
s1.fname = "Harry"
s1.mname = "Ginny"
s1.parent()

Output:

 

Working with Multiple Inheritance:

In a subclass, a parent class can be referred to using the super() function. It returns a temporary object of the superclass and this allows access to all of its methods to its child class. While using the super() keyword, we need not specify the parent class name to access its methods.

 

Example:

class Father:
   fname = ""
   def father(self):
      print(self.name)

class Mother:
   mname = ""
   def mother(self):
      print(self.name)

class Child(Father, Mother):
   def parents(self):
      super().__init__()
      print("Hello Everyone!!!")
      print("Father :", self.fname)
      print("Mother :", self.mname)

s1 = Child()
s1.fname = "Harry"
s1.mname = "Ginny"
s1.parent()

Output:

 

The super() function improves code reusability as there’s no need to rewrite the entire function.

 

Note:

  •       The class and its methods are referred to by the super function.
  •       The called function’s arguments and that of the super function must match.
  •       We must include ‘super()’ after every occurrence of the method.

 

Leave a comment