Computer >> Computer tutorials >  >> Programming >> Python

Inheritance in Python


In this article, we will learn inheritance and extending classes in Python 3.x. Or earlier.

Inheritance represents real-world relationships well, provides reusability & supports transitivity. It offers faster development time, easier maintenance and easy to extend.

Inheritance is broadly categorized into 5 types −

  • Single
  • Multiple
  • Hierarchical
  • Multi-level
  • Hybrid

Inheritance in Python

As shown in the figure above that inheritance is the process in which we try to access the features of other classes without actually making the object of the parent class.

Here we will be learning about the implementation of single and Hierarchical inheritances.

Single inheritance

Example

# parent class
class Student():
   # constructor of parent class
   def __init__(self, name, enrollnumber):
      self.name = name
      self.enrollnumber = enrollnumber
   def display(self):
      print(self.name)
      print(self.enrollnumber)
# child class
class College( Student ):
   def __init__(self, name, enrollnumber, admnyear, branch):
      self.admnyear = admnyear
      self.branch = branch
      # invoking the __init__ of the parent class
      Student.__init__(self, name, enrollnumber)
# creation of an object for base/derived class
obj = College('Rohit',42414802718,2018,"CSE")
obj.display()

Output

Rohit
42414802718

Multiple inheritance

Example

# parent class
class Student():
   # constructor of parent class
   def __init__(self, name, enrollnumber):
      self.name = name
      self.enrollnumber = enrollnumber
   def display(self):
      print(self.name)
      print(self.enrollnumber)
# child class
class College( Student ):
   def __init__(self, name, enrollnumber, admnyear, branch):
      self.admnyear = admnyear
      self.branch = branch
      # invoking the __init__ of the parent class
      Student.__init__(self, name, enrollnumber)
# child class
class University( Student ):
   def __init__(self, name, enrollnumber, refno, branch):
      self.refno = refno
      self.branch = branch
      # invoking the __init__ of the parent class
      Student.__init__(self, name, enrollnumber)
# creation of an object for base/derived class
obj_1 = College('Rohit',42414802718,2018,"CSE")
obj_1.display()
obj_2 = University ('Rohit',42414802718,"st2018","CSE")
obj_2.display()

Output

Rohit
42414802718
Rohit
42414802718

Conclusion

In this article, we learned about Inheritance in Python broadly single and hierarchical inheritance.