How does Python's super() work with multiple inheritance?


Before going to explain super() first we need to know about multiple inheritance concept.

Multiple inheritance : Means one child class can inherit multiple parent classes.

In the following example Child class inherited attributes methods from the Parent class.

Example

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

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

class Child(Father, Mother):
   def parent(self):
   print("Father :", self.fathername)
   print("Mother :", self.mothername)

s1 = Child()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent()

Output

Father : Srinivas
Mother : Anjali


In the following example shows ( i.e)  super() works with multiple inheritances

super() : The super function can be used to replace the explicit call to

Example

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

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

class Child(Father, Mother):
   def parent(self):
   super().__init__()
   print("i am here")
   print("Father :", self.fathername)
   print("Mother :", self.mothername)

s1 = Child()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent()

When you run the program, the output will be

Output

i am here
Father : Srinivas
Mother : Anjali

Sri
Sri

Updated on: 30-Jul-2019

735 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements