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
          self.Topic=Topic

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

    def printCourseDetails(self):
        print(Course.CourseName,Course.Topic,self.Authorname)

#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.
user_input=Author(input(),input(),input())
user_input.printCourseDetails()

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.

Input: 
Python
Inheritance 
Neha_Mishra 
Output: Python Inheritance Neha_Mishra

Leave a Reply

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