28. Problem to show inheritance in Python with example

In this Python oops program, we will create a class to show inheritance in Python with example. This code demonstrates the concept of inheritance

Inheritance in Python

Steps to solve the program
  1. The Person class has a constructor method __init__ that takes two parameters, name and age. Inside the constructor, the values of name and age are assigned to the instance variables self.name and self.age, respectively. This class also defines a method print_details that prints the name and age of the person.
  2. The Student class is a subclass of Person, as indicated by (Person) in its class definition. It adds two additional attributes, student_id and grades, which represent the student’s ID and grades, respectively. The class overrides the print_details method inherited from Person and extends it by calling the print_details method of the superclass using super().print_details(), and then printing the student ID.
  3. An object of the Student class is created with the name “Jade Smith”, age 24, student ID “A12345”, and grades [‘A’, ‘A+’]. The student variable now refers to this object.
  4. The print_details method is then called on the student object, which executes the overridden print_details method in the Student class. This method first calls the print_details method of the Person class using super().print_details() to print the person’s name and age, and then prints the student ID.

				
					class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def print_details(self):
        print("Name:", self.name)
        print("Age:", self.age)
        
class Student(Person):
    def __init__(self, name, age, student_id, grades):
        super().__init__(name, age)
        self.student_id = student_id
        self.grades = grades
    
    def print_details(self):
        super().print_details()
        print("Student ID:", self.student_id)

# Create an object of the Student class
student = Student("Jade Smith", 24, "A12345", ['A','A+'])
student.print_details()
				
			

Output:

				
					Name: Jade Smith
Age: 24
Student ID: A12345
				
			

Related Articles

Create a Python class called Person with attributes name and age.

Create a Python class called Cat that inherits from the Animal class.

Leave a Comment