Types of Inheritance in Python: A Beginner's Guide with Examples
By Rohan Vats
Updated on Oct 13, 2025 | 12 min read | 20.29K+ views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Oct 13, 2025 | 12 min read | 20.29K+ views
Share:
Table of Contents
Did you know? In 2025, Python’s dataclasses module just got a game-changing upgrade! Now, you can effortlessly inherit dataclass features in both dataclass and non-dataclass child classes, automatically reducing boilerplate and preventing common coding errors. This update is a significant win for Python developers! |
Inheritance in Python is a core concept that allows a class to acquire properties and methods from another class. It streamlines code, promotes reusability, and helps build organized programs. Python supports multiple inheritance types, including single, multiple, multilevel, hierarchical, and hybrid inheritance, each suited for specific scenarios. Understanding these types is essential for writing efficient, maintainable Python code.
In this blog, you will get a deep dive into the world of Python inheritance. We will start from the ground up, explaining what inheritance is and why it matters. Then, we'll explore each of the five types of inheritance in Python with clear, easy-to-understand code examples and diagrams. We will also cover best practices, discuss the pros and cons, and answer the most frequently asked questions to solidify your understanding.
Improve your coding skills with upGrad’s online software engineering courses. Specialize in cybersecurity, full-stack development, and much more. Take the next step in your learning journey!
Python is flexible and supports several different ways to structure class relationships. Understanding these structures helps you design your programs more effectively. There are primarily five types of inheritance in Python, each serving a different purpose.
Popular Data Science Programs
Here is a quick overview of the types we will cover:
Type of Inheritance | Description |
Single Inheritance | A child class inherits from a single parent class. |
Multiple Inheritance | A child class inherits from two or more parent classes. |
Multilevel Inheritance | A class inherits from a parent class, which in turn inherits from another parent. |
Hierarchical Inheritance | Multiple child classes inherit from a single parent class. |
Hybrid Inheritance | A combination of two or more of the above inheritance types. |
Let's explore each of these types of inheritance in Python in detail with code examples.
Single inheritance is the simplest and most common type of inheritance. In this form, a child class derives from exactly one parent class. This creates a direct, one-to-one hierarchical relationship.
Analogy: A child inheriting traits directly from one parent.
This is the foundational model for inheritance and is used extensively to create specialized versions of a general class. For instance, a Dog class can inherit from an Animal class. The Dog "is-a" type of Animal and will share common characteristics like eating and sleeping, but it will also have its own specific behaviors like barking.
Example of Single Inheritance:
Let's create a Person parent class and a Student child class. A student is a person, so they will share common attributes like a name and age, but a student will also have a unique attribute like a student ID.
Python
# Parent class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Child class inheriting from Person
class Student(Person):
def __init__(self, name, age, student_id):
# Initialize the parent class attributes
super().__init__(name, age)
self.student_id = student_id
def display_student_info(self):
# We can call the parent method from the child
self.display_info()
print(f"Student ID: {self.student_id}")
# Create an object of the Student class
student1 = Student("Alice", 20, "S12345")
student1.display_student_info()
Output:
Name: Alice, Age: 20
Student ID: S12345
Here, the Student class inherits all the functionality of the Person class and extends it with its own. The super().__init__(name, age) call is crucial; it ensures that the parent class's __init__ method is called, properly setting up the name and age attributes. This is the core idea of single inheritance in Python.
Also Read: Discover the Secrets of Method Overriding in Python!
Multiple inheritance is a powerful feature where a child class can inherit from more than one parent class. This allows the child class to combine the features of all its parents.
Analogy: A child inheriting different skills from both parents, like artistic talent from one and analytical skills from the other.
While powerful, multiple inheritance can also introduce complexity. If multiple parent classes have a method with the same name, it can create ambiguity. Python solves this using a specific algorithm called Method Resolution Order (MRO) to determine which parent's method to call.
Example of Multiple Inheritance:
Imagine we have a Flying class and a Swimming class. We want to create a Duck class that can both fly and swim. Multiple inheritance is perfect for this.
Data Science Courses to upskill
Explore Data Science Courses for Career Progression
Python
# First parent class
class Flyer:
def fly(self):
print("This creature can fly.")
# Second parent class
class Swimmer:
def swim(self):
print("This creature can swim.")
# Child class inheriting from both Flyer and Swimmer
class Duck(Flyer, Swimmer):
def quack(self):
print("Quack quack!")
# Create an object of the Duck class
donald = Duck()
# Call methods from all parent classes and its own class
donald.fly()
donald.swim()
donald.quack()
Output:
This creature can fly.
This creature can swim.
Quack quack!
As you can see, the Duck object can now use methods from Flyer, Swimmer, and its own class. This is one of the more advanced types of inheritance in Python.
A key concept here is the MRO. It defines the order in which Python searches for a method in the hierarchy of classes.
You can view the MRO of a class using ClassName.mro(). For our Duck class, the MRO would be [<class '__main__.Duck'>, <class '__main__.Flyer'>, <class '__main__.Swimmer'>, <class 'object'>].
This means Python first looks for a method in Duck, then Flyer, then Swimmer, and finally in the base object class.
Also Read: OOPs Concepts in Python: Classes, Objects, and Implementation Guide
In multilevel inheritance, you have a chain of inheritance. A derived class inherits from a base class, and then another class inherits from this derived class. It's like a grandparent-parent-child relationship.
Analogy: A grandchild inherits traits from their parent, who in turn inherited traits from their own parent (the grandparent).
This type of inheritance is useful for modeling real-world relationships that have multiple levels of hierarchy.
Example of Multilevel Inheritance:
Let's model a hierarchy of electronic devices. We'll have a base Device class, a Phone class that inherits from Device, and a Smartphone class that inherits from Phone.
Python
# Grandparent class
class Device:
def turn_on(self):
print("Device is turned on.")
# Parent class inheriting from Device
class Phone(Device):
def make_call(self):
print("Making a call...")
# Child class inheriting from Phone
class Smartphone(Phone):
def browse_internet(self):
print("Browsing the internet...")
# Create an object of the Smartphone class
my_phone = Smartphone()
# The Smartphone object can access methods from all its ancestors
my_phone.turn_on() # From Device class
my_phone.make_call() # From Phone class
my_phone.browse_internet() # From its own class
Output:
Device is turned on.
Making a call...
Browsing the internet...
Here, Smartphone inherits from Phone, and Phone inherits from Device. This allows the Smartphone class to access methods from both Phone and Device, creating a clear and logical multilevel structure. This is a very common pattern among the different types of inheritance in Python.
Also Read: Top 36+ Python Projects for Beginners and Students to Explore in 2025
Hierarchical inheritance is the opposite of multiple inheritance. In this pattern, one parent class serves as the base for multiple child classes. It's a one-to-many relationship.
Analogy: A single parent having multiple children. Each child inherits from the parent but also has their own unique characteristics.
This is extremely useful when you have a general category and want to create several specific items under it. For example, a Shape class could be the parent for Circle, Square, and Triangle classes.
Example of Hierarchical Inheritance:
Let's use the Employee class as a parent. From it, we can derive several specific roles like Developer and Manager. Both are employees and share common attributes, but their roles and responsibilities differ.
Python
# Parent class
class Employee:
def __init__(self, name, employee_id):
self.name = name
self.employee_id = employee_id
def show_details(self):
print(f"Name: {self.name}, ID: {self.employee_id}")
# First child class
class Developer(Employee):
def work(self):
print(f"{self.name} is writing code.")
# Second child class
class Manager(Employee):
def work(self):
print(f"{self.name} is managing the team.")
# Create objects of the child classes
dev1 = Developer("Charlie", "E101")
mgr1 = Manager("Dana", "E102")
dev1.show_details()
dev1.work()
print("-" * 20)
mgr1.show_details()
mgr1.work()
Output:
Name: Charlie, ID: E101
Charlie is writing code.
--------------------
Name: Dana, ID: E102
Dana is managing the team.
In this structure, both Developer and Manager inherit from Employee and can use the show_details() method. However, they each have their own specialized work() method. This is a great example of hierarchical inheritance in Python.
Also Read: Unveiling the Power of SQL with Python
Hybrid inheritance is a combination of two or more of the other types of inheritance. When a program's class structure becomes complex, it might not fit neatly into a single inheritance type. For example, you might have a mix of multilevel and multiple inheritance.
Analogy: A complex family tree that involves multiple generations and relationships, where a person can be a child, a parent, and a grandchild all at once in different contexts.
The most famous problem associated with hybrid inheritance is the "Diamond Problem," which arises when a class inherits from two classes that share a common ancestor. Python's Method Resolution Order (MRO) is designed specifically to handle this scenario gracefully, ensuring there is a clear, predictable path for method calls. This makes using hybrid inheritance in Python safe and manageable.
Example of Hybrid Inheritance:
Let's create a classic Diamond Problem scenario to see how Python handles it.
Python
class University:
def show_name(self):
print("This is a University.")
class Department1(University):
def greet(self):
print("Welcome from Department 1.")
class Department2(University):
def greet(self):
print("Greetings from Department 2.")
# This class inherits from both Department1 and Department2
class Student(Department1, Department2):
pass
# Create an object and call the methods
student = Student()
student.show_name() # Inherited from University through both paths
student.greet() # Which greet() method will be called?
# Let's inspect the Method Resolution Order (MRO)
print(Student.mro())
Output:
This is a University.
Welcome from Department 1.
[<class '__main__.Student'>, <class '__main__.Department1'>, <class '__main__.Department2'>, <class '__main__.University'>, <class 'object'>]
Here, Student inherits from both Department1 and Department2, which both inherit from University. When we call student.greet(), Python follows the MRO. According to the MRO list, it checks Student first, then Department1, then Department2, and finally University. Since Department1 is listed before Department2, its greet() method is called. This predictable behavior is what makes even complex types of inheritance in Python reliable.
Also Read: Multiple Inheritance in Python
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
After looking at the different types of inheritance in Python, let's undertand a fundamental question: what is inheritance in Python? At its core, inheritance is a mechanism that allows a new class to inherit properties, attributes and methods, from an existing class. This creates an "is-a" relationship between the two classes.
Think of it like biological inheritance. You inherit certain traits, like eye color or height, from your parents. Similarly, in Python, a new class can be created that inherits the characteristics of another class.
The primary motivation behind inheritance is code reusability. Instead of writing the same code over and over again for different classes that share some logic, you can write it once in a parent class. Then, any child class that inherits from it automatically gets access to that code.
Let's look at a simple example to explain inheritance in Python:
Python
# Parent class
class Vehicle:
def __init__(self, brand, year):
self.brand = brand
self.year = year
print("Vehicle instance created.")
def start_engine(self):
print("Engine started!")
# Child class inheriting from Vehicle
class Car(Vehicle):
def __init__(self, brand, year, model):
# Call the parent class constructor
super().__init__(brand, year)
self.model = model
print("Car instance created.")
def honk(self):
print("Beep beep!")
# Create an object of the Car class
my_car = Car("Toyota", 2023, "Corolla")
# Access methods from both parent and child classes
my_car.start_engine() # Inherited from Vehicle
my_car.honk() # Defined in Car
# Access attributes from the parent class
print(f"Brand: {my_car.brand}, Model: {my_car.model}")
In this example, the Car class is the child class, and Vehicle is the parent. Car inherits the __init__ method (partially, using super()) and the start_engine() method from Vehicle. It also adds its own unique method, honk(). This way, we don't have to rewrite the engine logic for every new type of vehicle we create. This simple concept is the foundation for building complex and well-structured software.
Also Read: Master Pattern Programs in Python: 20+ Star & Number Patterns with Code
Inheritance is a powerful tool, but like any tool, it must be used correctly. Misusing inheritance can lead to code that is complex, rigid, and hard to maintain. Here are some best practices to follow when working with the various types of inheritance in Python.
By keeping these principles in mind, you can leverage the power of all types of inheritance in Python to build robust, maintainable, and well-designed software.
Also Read: 25 Must-Try Machine Learning Projects in Python for Beginners and Experts in 2025
Like any programming concept, inheritance comes with its own set of trade-offs. It is essential to understand both the benefits and the drawbacks to decide when it is the right tool for the job. Here's a summary of the pros and cons of using inheritance in your Python projects.
Advantages | Disadvantages |
---|---|
Code Reusability – Write common code once and reuse it in multiple child classes. | Tight Coupling – Changes in the parent class can affect all child classes. |
Logical Structure – Clear "is-a" relationship makes code easier to understand. | Increased Complexity – Deep or multiple inheritance can make code harder to trace. |
Extensibility – Extend functionality by creating new child classes without modifying parent code. | Slower Runtime – Method lookups may be slower due to class hierarchy traversal. |
Polymorphism – Treat child objects as parent type for flexible, generic code. | Incorrect Abstraction – Wrong "is-a" modeling can lead to flawed design; sometimes "has-a" (composition) is better. |
Ultimately, inheritance is a powerful feature when used appropriately. By understanding these pros and cons, you can make informed decisions about your application's architecture and choose the best approach for organizing your code.
Also Read: What is Polymorphism in Python? Polymorphism Explained with Examples
Next, let’s look at how upGrad can assist in your learning journey.
Inheritance in Python offers powerful ways to organize and reuse code, allowing you to create more efficient and maintainable applications. However, mastering inheritance in Python can be challenging, especially when dealing with complex hierarchies or multiple inheritance scenarios.
To excel, focus on practicing with simple examples, then gradually build more intricate systems to gain confidence. For further growth in your Python journey, upGrad’s courses in Python and OOPs can deepen your understanding and help you tackle more advanced challenges.
In addition to the courses mentioned above, here are some more free courses that can help you elevate your skills:
Not sure which direction to take in your career or feeling uncertain about your next step? You can get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals
Inheritance is a mechanism where one class acquires the properties of another (an "is-a" relationship). Polymorphism, on the other hand, is the ability of an object to take on many forms; typically, this means a parent class reference can be used to refer to a child class object, allowing the same method name to behave differently for different classes.
Yes, Python supports multiple inheritance, which means a single child class can inherit from two or more parent classes. This allows the child class to combine the functionalities of all its parents.
The super() function is used to call a method from the parent class. It is most commonly used in a child class's __init__ method to call the parent's __init__ method, ensuring that the parent's attributes are properly initialized.
Python uses an algorithm called C3 linearization to determine the Method Resolution Order (MRO). The MRO provides a consistent and predictable order for searching methods in the class hierarchy, which resolves any ambiguity that might arise from the Diamond Problem.
An Abstract Base Class is a class that cannot be instantiated on its own and is meant to be inherited from. It defines a set of methods and properties that its subclasses are required to implement, thus enforcing a common interface.
No, it is not mandatory. If a child class does not define its own __init__ method, it will automatically inherit the __init__ method of its parent class.
In Python, there are no truly "private" members. Members prefixed with a double underscore (e.g., __secret) are name-mangled, making them harder to access from outside the class but not impossible. A child class does not directly inherit these name-mangled attributes.
In single inheritance, a child class inherits from only one parent class. In multilevel inheritance, a class inherits from a parent class, which itself is a child class of another parent, creating a chain-like hierarchy (e.g., Grandparent -> Parent -> Child).
You should use inheritance for "is-a" relationships (a Car is a Vehicle). Use composition for "has-a" or "uses-a" relationships (a Car has an Engine). Composition is often more flexible and leads to a more loosely coupled design.
The object class is the ultimate base class for all classes in Python. If a class is defined without specifying a parent, it implicitly inherits from object.
Yes, a child class can provide its own implementation for a method that is already defined in its parent class. This is called method overriding and is a key feature of polymorphism.
You can use the built-in function issubclass(SubClass, SuperClass). It returns True if SubClass is a direct or indirect subclass of SuperClass, and False otherwise.
The MRO defines the order in which base classes are searched when looking for a method. It is crucial in multiple and hybrid inheritance to resolve which method to execute when multiple parent classes have methods with the same name.
Yes. If a child class does not define its own __init__ constructor, it will inherit the __init__ method from its parent class automatically.
Python does not have a formal interface keyword like Java. However, the concept of an interface can be implemented using Abstract Base Classes (ABCs) from the abc module, which can define methods that subclasses must implement.
A mixin is a class that provides a specific, standalone functionality and is designed to be inherited by other classes, but not to be instantiated on its own. It's a way to use multiple inheritance to add features to a class without creating a complex "is-a" relationship.
While Python doesn't have a final keyword like in Java, you can use name mangling (prefixing the method name with a double underscore, e.g., __method_name) to make it difficult for a subclass to accidentally override it.
No, a class cannot inherit from itself, either directly or indirectly. Attempting to do so will result in a TypeError because it would create an infinite loop in the inheritance hierarchy.
Python's Method Resolution Order (MRO) determines which method is called. Python will call the method from the class that appears first in the MRO list, providing a clear and non-ambiguous resolution.
Not always. While powerful, inheritance can lead to tightly coupled and rigid code if overused or misused. It's important to evaluate if an "is-a" relationship truly exists and to consider alternatives like composition, which often leads to more flexible and maintainable designs.
408 articles published
Rohan Vats is a Senior Engineering Manager with over a decade of experience in building scalable frontend architectures and leading high-performing engineering teams. Holding a B.Tech in Computer Scie...
Speak with Data Science Expert
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources