Python Program to Implement Inheritance

Introduction

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class (called the child or subclass) to inherit attributes and methods from an existing class (called the parent or superclass). This enables code reuse and the creation of hierarchical class structures, where specialized classes share common behavior from more general classes.

This tutorial will guide you through creating a Python program that demonstrates inheritance by defining a parent class and a child class that inherits from the parent class.

Example:

  • Parent Class: Person
  • Child Class: Student
  • Attributes: name, age (inherited by Student), student_id (specific to Student)
  • Methods: display_info() (inherited and extended by Student)
  • Program Output:
    Name: Alice, Age: 20, Student ID: S12345
    

Problem Statement

Create a Python program that:

  • Defines a parent class named Person with attributes name and age, and a method display_info.
  • Defines a child class named Student that inherits from Person, adds an additional attribute student_id, and extends the display_info method.
  • Creates an object of the Student class and calls the display_info method to demonstrate inheritance.

Solution Steps

  1. Define the Parent Class: Use the class keyword to define a class named Person.
  2. Add an Initialization Method: Define the __init__ method to initialize the name and age attributes.
  3. Add a Method: Define a method named display_info to print the person’s details.
  4. Define the Child Class: Use the class keyword to define a class named Student that inherits from Person.
  5. Extend the Initialization Method: Extend the __init__ method to include student_id in the Student class.
  6. Override the Method: Override and extend the display_info method in the Student class.
  7. Create an Object: Instantiate an object of the Student class.
  8. Call the Method: Call the display_info method on the Student object to display the details.

Python Program

# Python Program to Implement Inheritance
# Author: https://www.rameshfadatare.com/

# Step 1: Define the Parent Class
class Person:
    # Step 2: Add an Initialization Method
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    # Step 3: Add a Method
    def display_info(self):
        print(f"Name: {self.name}, Age: {self.age}")

# Step 4: Define the Child Class
class Student(Person):
    # Step 5: Extend the Initialization Method
    def __init__(self, name, age, student_id):
        # Call the __init__ method of the parent class
        super().__init__(name, age)
        self.student_id = student_id
    
    # Step 6: Override the Method
    def display_info(self):
        super().display_info()  # Call the parent class method
        print(f"Student ID: {self.student_id}")

# Step 7: Create an Object of the Student Class
student = Student("Alice", 20, "S12345")

# Step 8: Call the Method to Display Student Details
student.display_info()

Explanation

Step 1: Define the Parent Class

  • The Person class is defined using the class keyword. This class serves as the parent (or base) class.

Step 2: Add an Initialization Method

  • The __init__ method initializes the attributes name and age for the Person class. These attributes are shared with any class that inherits from Person.

Step 3: Add a Method

  • The display_info method is defined to print the name and age of a person.

Step 4: Define the Child Class

  • The Student class is defined using the class keyword and inherits from the Person class. This is indicated by the syntax class Student(Person):.

Step 5: Extend the Initialization Method

  • The Student class extends the __init__ method by adding an additional attribute student_id. The super().__init__(name, age) call invokes the __init__ method of the parent class to initialize the name and age attributes.

Step 6: Override the Method

  • The Student class overrides the display_info method to include the student_id in the output. The super().display_info() call is used to invoke the display_info method of the parent class.

Step 7: Create an Object

  • An object student is created by calling the Student class with specific arguments for name, age, and student_id.

Step 8: Call the Method

  • The display_info method is called on the student object to print the student’s details, demonstrating the inheritance of attributes and methods.

Output Example

Example Output:

Name: Alice, Age: 20
Student ID: S12345

Additional Examples

Example 1: Inheritance with Multiple Levels

# Define a class GraduateStudent that inherits from Student
class GraduateStudent(Student):
    def __init__(self, name, age, student_id, thesis_title):
        super().__init__(name, age, student_id)
        self.thesis_title = thesis_title
    
    def display_info(self):
        super().display_info()
        print(f"Thesis Title: {self.thesis_title}")

# Create an object of the GraduateStudent class
grad_student = GraduateStudent("Bob", 25, "G98765", "Machine Learning in Healthcare")
grad_student.display_info()

Output:

Name: Bob, Age: 25
Student ID: G98765
Thesis Title: Machine Learning in Healthcare

Example 2: Inheritance with Method Overriding

# Define a class Teacher that inherits from Person
class Teacher(Person):
    def __init__(self, name, age, subject):
        super().__init__(name, age)
        self.subject = subject
    
    def display_info(self):
        super().display_info()
        print(f"Subject: {self.subject}")

# Create an object of the Teacher class
teacher = Teacher("Dr. Smith", 45, "Physics")
teacher.display_info()

Output:

Name: Dr. Smith, Age: 45
Subject: Physics

Example 3: Inheritance Without Method Overriding

# Define a class Employee that inherits from Person without overriding methods
class Employee(Person):
    def __init__(self, name, age, employee_id):
        super().__init__(name, age)
        self.employee_id = employee_id

# Create an object of the Employee class
employee = Employee("John", 30, "E123")
employee.display_info()  # Inherited method from Person class

Output:

Name: John, Age: 30

Conclusion

This Python program demonstrates how to implement inheritance, a key concept in object-oriented programming. Inheritance allows you to create new classes that are based on existing classes, promoting code reuse and hierarchical class structures. By understanding inheritance, you can write more organized, maintainable, and scalable Python programs.

Leave a Comment

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

Scroll to Top