Mastering Python Inheritance: Concepts, Syntax, and Practical Examples
Python Inheritance
Inheritance lets you create a new class that inherits all functionality from a parent class while adding or extending features. This tutorial explains how to use inheritance in Python, with clear examples and best‑practice guidance.
Video: Python Inheritance
Inheritance in Python
Inheritance is a core principle of object‑oriented programming that promotes code reuse and logical hierarchy. A new class (the derived or child class) is defined with minimal or no changes to an existing class (the base or parent class). The child class automatically receives the attributes and methods of its parent, which can then be overridden or extended as needed.
Python Inheritance Syntax
class BaseClass:
# body of base class
class DerivedClass(BaseClass):
# body of derived class
In the snippet above, DerivedClass inherits all public members from BaseClass. By adding new methods or overriding existing ones, the derived class can customize behavior while reusing the base implementation.
Example of Inheritance in Python
Let’s illustrate inheritance with a practical example. Suppose we have a generic Polygon class that stores the number of sides and their lengths:
class Polygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for _ in range(no_of_sides)]
def input_sides(self):
self.sides = [float(input(f"Enter side {i+1} : ")) for i in range(self.n)]
def display_sides(self):
for i, side in enumerate(self.sides, 1):
print(f"Side {i} is {side}")
The Polygon class encapsulates common attributes and methods for any polygon. A Triangle is a specific polygon with exactly three sides, so it can inherit from Polygon without redefining the shared logic:
class Triangle(Polygon):
def __init__(self):
super().__init__(3) # initialize base with 3 sides
def find_area(self):
a, b, c = self.sides
s = (a + b + c) / 2
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
print(f"The area of the triangle is {area:.2f}")
Running the following demonstrates the inheritance in action:
>>> t = Triangle()
>>> t.input_sides()
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4
>>> t.display_sides()
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0
>>> t.find_area()
The area of the triangle is 6.00
Notice that Triangle can call input_sides() and display_sides() even though it never defines them—inheritance makes these methods available automatically.
If an attribute or method is not found in the child class, Python searches the parent class, and this lookup continues up the inheritance chain if needed.
Method Overriding in Python
Both Polygon and Triangle define an __init__ method. The child’s implementation overrides the parent’s, but it can (and should) extend the base logic by invoking it explicitly. Using super() is the modern, preferred approach:
class Triangle(Polygon):
def __init__(self):
super().__init__(3) # calls Polygon.__init__
When overriding, the child method can add new behavior or modify the base behavior while preserving the original functionality.
Python provides isinstance() and issubclass() to introspect inheritance relationships:
t = Triangle()
print(isinstance(t, Triangle)) # True
print(isinstance(t, Polygon)) # True
print(isinstance(t, int)) # False
print(isinstance(t, object)) # True
print(issubclass(Polygon, Triangle)) # False
print(issubclass(Triangle, Polygon)) # True
print(issubclass(bool, int)) # True
These utilities are essential for type checking and ensuring that objects conform to expected interfaces.
For more on super(), see the Python super() function documentation.
Python
- Mastering C# Inheritance: Concepts, Types, and Practical Code
- Master C++ Inheritance: Build Powerful Classes with Reusable Code
- Mastering Python Custom Exceptions: A Practical Guide
- Master Python Multiple Inheritance, Multilevel Inheritance, and Method Resolution Order (MRO)
- Mastering Operator Overloading in Python: A Practical Guide
- Mastering Python’s @property Decorator: Clean, Backward‑Compatible Getters & Setters
- Mastering Java Inheritance: Concepts, Types, and Practical Examples
- Python OOP Fundamentals: Classes, Objects, Inheritance, and Constructors Explained
- Mastering Python Class Slots: Optimize Memory & Speed
- Mastering C# Inheritance: Build Reusable, Maintainable Code