Member-only story
Mastering Single Inheritance in Python: Explained with Real-World Examples
Introduction
In object-oriented programming, inheritance is a mechanism where a new class (called the child or subclass) is derived from an existing class (called the parent or superclass), inheriting all its properties and methods. Single inheritance is a type of inheritance where a subclass inherits properties and methods from a single parent class.
Python, being an object-oriented language, supports single inheritance. In this article, we will explore single inheritance in Python with several examples.
Example 1: Inheriting from a Parent Class
Let’s start with a simple example that demonstrates how to inherit from a parent class. Suppose we have a class Person
that has two properties (name
and age
) and a method (print_info()
) that prints the name and age of the person:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def print_info(self):
print(f"{self.name} is {self.age} years old")
Now, let’s create a class Student
that inherits from Person
and adds a new property (grade
) and a new method (print_info()
) that prints the name, age, and grade of the student: