Saturday, February 8, 2020

Inheritance in Python

Inheritance in Python


Inheritance


Inheritance is a concept from object-oriented programming techniques. Inheritance is a concept that enables a Python class to acquire the properties of another class. The acquiring class is known as some class and the class from which this class is acquiring the property is known as a superclass.

The advantages of inheritance are code reuse, high readability of code, reducing complexity. Inheritance provides the "IS-A" relationship between class. It means we can read like "Class AIS-A subclass of Class B".


Inheritance in Python
Inheritance


Advantages of Inheritance


  • Code reuse
  • High readability of code
  • Inheritance provides the platform for polymorphism
  • Reducing complexity


There are basically two classes involved in the inheritance 

  • Superclass or Parent class
  • Subclass or Child class

Python is an object-oriented programming language, it also provides inheritance. To understand how Python provides inheritance we can look into this example. Superclass is created normally as we create another class. To create a subclass, we need to provide the name of the superclass between parenthesis, between the name of the class and colon during the declaration of the subclass.

Using Inheritance

 

#inheritance demo
class animal:     #SUPER CLASS
  def __init__(self,color):   #SUPER CLASS INITIALIZER
    self.color=color
    
  def display(self):    #METHOD IN SUPER CLASS
    print('This Animal\'s color is '+ self.color)

class dog(animal):      #SUB CLASS
  def __init__(self,color,breed):   #SUB CLASS INITIALIZER
    super().__init__(color)    #USING SUPER CLASS INITIALIZER
    #OR
    # animal.__init(color)    #USING SUPER CLASS INITIALIZER
    self.breed=breed
    
  def describe(self):   #METHOD IN SUB CLASS
    print('this animal is dog and the breed is '+self.breed)
 #SINGLE INHERITANCE   
a=animal('BLACK')
d=dog('BLACK','PUG')
a.display()   #SUPER CLASS METHOD
d.display()   #SUPER CLASS METHOD
d.describe()    #SUB CLASS METHOD

Output:
This Animal's color is BLACK
This Animal's color is BLACK
this animal is dog and the breed is PUG

super


Python also has super(), which can be used to refer to the superclass initializer, member, or method. the super() function is very much like the "super" keyword in Java. There are various type of Inheritance in Python,
  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance
You can see them in more detail in this example.