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 byStudent
),student_id
(specific toStudent
) - Methods:
display_info()
(inherited and extended byStudent
) - Program Output:
Name: Alice, Age: 20, Student ID: S12345
Problem Statement
Create a Python program that:
- Defines a parent class named
Person
with attributesname
andage
, and a methoddisplay_info
. - Defines a child class named
Student
that inherits fromPerson
, adds an additional attributestudent_id
, and extends thedisplay_info
method. - Creates an object of the
Student
class and calls thedisplay_info
method to demonstrate inheritance.
Solution Steps
- Define the Parent Class: Use the
class
keyword to define a class namedPerson
. - Add an Initialization Method: Define the
__init__
method to initialize thename
andage
attributes. - Add a Method: Define a method named
display_info
to print the person’s details. - Define the Child Class: Use the
class
keyword to define a class namedStudent
that inherits fromPerson
. - Extend the Initialization Method: Extend the
__init__
method to includestudent_id
in theStudent
class. - Override the Method: Override and extend the
display_info
method in theStudent
class. - Create an Object: Instantiate an object of the
Student
class. - Call the Method: Call the
display_info
method on theStudent
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 theclass
keyword. This class serves as the parent (or base) class.
Step 2: Add an Initialization Method
- The
__init__
method initializes the attributesname
andage
for thePerson
class. These attributes are shared with any class that inherits fromPerson
.
Step 3: Add a Method
- The
display_info
method is defined to print thename
andage
of a person.
Step 4: Define the Child Class
- The
Student
class is defined using theclass
keyword and inherits from thePerson
class. This is indicated by the syntaxclass Student(Person):
.
Step 5: Extend the Initialization Method
- The
Student
class extends the__init__
method by adding an additional attributestudent_id
. Thesuper().__init__(name, age)
call invokes the__init__
method of the parent class to initialize thename
andage
attributes.
Step 6: Override the Method
- The
Student
class overrides thedisplay_info
method to include thestudent_id
in the output. Thesuper().display_info()
call is used to invoke thedisplay_info
method of the parent class.
Step 7: Create an Object
- An object
student
is created by calling theStudent
class with specific arguments forname
,age
, andstudent_id
.
Step 8: Call the Method
- The
display_info
method is called on thestudent
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.