Sure!
Let’s explore two common types of inheritance in Python: Single Inheritance and
Multiple Inheritance.
1. Single Inheritance
In single inheritance, a child class inherits from only one parent class. This is the simplest
form of inheritance.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def display_student(self):
print(f"Student ID: {self.student_id}")
# Creating an instance of Student
student = Student("Alice", 20, "S12345")
student.display() # Inherited method
student.display_student() # Child class method
In this example, the Student class inherits from the Person class. The Student class can
access the display method from the Person class.
2. Multiple Inheritance
In multiple inheritance, a child class inherits from more than one parent class. This allows the
child class to access attributes and methods from multiple parent classes.
Example:
class Teacher:
def __init__(self, subject):
self.subject = subject
def teach(self):
print(f"Teaching: {self.subject}")
class Researcher:
def __init__(self, field):
self.field = field
def research(self):
print(f"Researching: {self.field}")
class Professor(Teacher, Researcher):
def __init__(self, name, subject, field):
Teacher.__init__(self, subject)
Researcher.__init__(self, field)
self.name = name
def display(self):
print(f"Professor {self.name} teaches {self.subject} and researches
{self.field}")
# Creating an instance of Professor
prof = Professor("Dr. Smith", "Mathematics", "Algebra")
prof.display() # Method from Professor class
prof.teach() # Method from Teacher class
prof.research() # Method from Researcher class
In this example, the Professor class inherits from both Teacher and Researcher classes.
The Professor class can access methods from both parent classes.