Concept of Inheritance, Superclass and Subclass in Python

Here we are going to learn the basic concepts of Inheritance in Python. In order to understand what inheritance is we should first dive in superclass and subclass.

Concept of Inheritance in Python


In any object-oriented programming language, the variables and methods of a class can be reused again in another class through inheritance. Thus we can define new class having similar functionality to that of a pre-defined class with little modifications by adding new functionalities to it as per the requirement. To understand the concept of inheritance, we need to learn about two types of classes in reference to which inheritance is defined. These two classes are superclass and subclass.

The class whose properties gets inherited by another class is known as superclass or parent class and the class which inherits the properties of another class is known as the subclass. A subclass inherits all data and behavior of parent class. But we can also add more information and behavior to the subclass and also override its behavior.

Inheritance is the property of an OOP language through which the data and behavior of a superclass can be passed onto a subclass. It forms a tree hierarchy where parent class is the root and subsequent subclasses are the leaves derived from their parent class.

Here is the code which shows implementation of inheritance:

# Parent Class
class Course(object):
      # Constructor 
      def __init__(self, CourseName,Topic): 
          self.CourseName =CourseName

# Inherited or Sub class  
class Author(Course): 
    def __init__(self,CourseName,Topic,Authorname):
        #deriving attributes of Parent Class
        #adding a new attribute to the subclass

    def printCourseDetails(self):

#The three consecutive inputs will take name of the course,one of the topics from that course and the name of author who writes a post for that topic and will print them in order.

In this example, ‘Course’ is the parent class with two data attributes ‘CourseName’ and ‘Topic’ while ‘Author’ is the subclass which derived both the attributes of ‘Course’ and we have added one more attribute to it named as ‘Authorname’.

Let’s see how this code will work.

Output: Python Inheritance Neha_Mishra

Leave a Reply

Your email address will not be published. Required fields are marked *