Write a python program to Multilevel inheritance


This Python program defines a class hierarchy with multilevel inheritance in Python. Here's a breakdown of the classes and their relationships:

  • Person (Base class): This class has a constructor __init__ that initializes the name and age attributes. It also has a display_info method that prints the name and age.
  • Student (Intermediate class): This class inherits from Person and adds a new attribute student_id. It has its constructor, which takes the name, age, and student_id as parameters. The constructor of the Student class calls the constructor of the Person class using super() to set the name and age. It also has a display_student_info method, which calls the display_info method from the Person class and adds the student_id information.
  • GraduateStudent (Derived class): This class inherits from Student and adds a new attribute research_topic. It has its constructor, which takes the name, age, student_id, and research_topic as parameters. The constructor of the GraduateStudent class calls the constructor of the Student class using super() to set the name, age, and student_id. It also has a display_graduate_info method, which calls the display_student_info method from the Student class and adds the research_topic information.

You create an instance of the GraduateStudent class with the name "Alice," age 25, student ID "STU001," and a research topic of "Machine Learning." Then, you call the display_graduate_info method on the graduate_student object, which prints out all the information from the base Person class, the Student class, and the GraduateStudent class, including the research topic.


Source Code

class Person:	# Base class
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def display_info(self):
        print("Name : ",self.name)
        print("Age : ",self.age)
 
class Student(Person):	# Intermediate class inheriting from Person
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id
 
    def display_student_info(self):
        super().display_info()
        print("Student ID : ",self.student_id)
 
 
class GraduateStudent(Student):	 # Derived class inheriting from Student
    def __init__(self, name, age, student_id, research_topic):
        super().__init__(name, age, student_id)
        self.research_topic = research_topic
 
    def display_graduate_info(self):
        super().display_student_info()
        print("Research Topic : ",self.research_topic)
 
# Create an instance of GraduateStudent
graduate_student = GraduateStudent("Alice", 25, "STU001", "Machine Learning")
 
# Display information using the multilevel inheritance
graduate_student.display_graduate_info()

Output

Name :  Alice
Age :  25
Student ID :  STU001
Research Topic :  Machine Learning

Example Programs