Python Inheritance Explained: Types and Use Cases
What is inheritance in Python
Inheritance in Python is a fundamental concept in Object-Oriented Programming (OOP) that allows one class (the child class) to acquire properties and behaviors from another class (the parent class). This helps in code reusability, organization, and hierarchy maintenance, making it easier to manage and extend functionalities without rewriting code.
The benefits of using inheritance are as follows:
- Code Reusability: Child classes can make use of existing codes, which reduces redundancy.
- Extensibility: Additional functionalities can easily be incorporated into child classes, which makes it easier for programs to be extended without changing the parent class.
- Improved Code Structure: Helps in organizing related classes and maintaining relationships between them.
- Encapsulation & Maintainability: Enables the better organization of data and behavior within related classes.
To see how inheritance works in action, let’s take a real-world analogy. Think of a general “Vehicle” class that defines common properties like wheels
and engine()
. A “Car” class can inherit from “Vehicle” and add its own unique features like air_conditioning()
. Similarly, a “Bike” class can inherit from “Vehicle” but have a kick_start()
method instead of an engine start button.
Now that we understand inheritance let’s explore how Python applies it to real-world scenarios with practical examples.
Learn Java: Inheritance and Polymorphism
Learn how to go further with classes by using inheritance and polymorphism.Try it for freeUnderstanding Python inheritance
In Python, a class can inherit from another class by specifying the parent class in parentheses. Here is the syntax for the same:
class ParentClass: # Parent class attributes and methods class ChildClass(ParentClass): # Child class attributes and methods
- The child class automatically gets all the attributes and methods of the parent class.
- The child class can also add new features or override existing ones from the parent class.
Let’s understand inheritance with a relatable example.
Imagine a company where employees have common attributes, but managers enjoy additional perks. We can represent this in Python as follows:
# Parent class - EmployeeclassEmployee:def__init__(self, name, department):self.name = nameself.department = departmentdefwork(self):returnf"{self.name} from {self.department} is responding to emails... and pretending to be busy."# Child class - Manager inherits from EmployeeclassManager(Employee):defschedule_meeting(self):returnf"{self.name} has scheduled a 'quick' 2-hour meeting. Everyone, brace yourselves!"# Child class - Intern inherits from EmployeeclassIntern(Employee):deffetch_coffee(self):returnf"{self.name} is on yet another coffee run... productivity at its peak!"# Creating employee objectsalice = Manager("Alice","Marketing")bob = Intern("Bob","Software Engineering")print(alice.work())print(alice.schedule_meeting())# Accessing inherited and unique methodsprint(bob.work())print(bob.fetch_coffee())
The output produced by this code is as follows:
Alice from Marketing is responding to emails... and pretending to be busy.Alice has scheduled a 'quick' 2-hour meeting. Everyone, brace yourselves!Bob from Software Engineering is responding to emails... and pretending to be busy.Bob is on yet another coffee run... productivity at its peak!
Let’s break this code down to see how inheritance helps structure our corporate hierarchy:
- Employee (Parent Class): Defines shared attributes (
name
,department
) and awork()
method. - Manager (Child Class): Inherits from
Employee
and addsschedule_meeting()
. - Intern (Child Class): Inherits from
Employee
and addsfetch_coffee()
. - Inheritance in Action: Both child classes reuse
Employee
features while introducing their own.
This was a basic case, but Python offers more ways to structure class relationships. Let’s explore them in the next section.
Types of inheritance in Python
Inheritance in Python isn’t just about a single parent-child relationship. Depending on the structure of classes, Python offers multiple types of inheritance to suit different needs. Let’s understand the different types.
Single inheritance
Single inheritance is the simplest form of inheritance, where a child class inherits from a single parent class. It allows the child class to reuse the functionality of the parent while also adding its own unique features.
An example of this could be:
classAnimal:defwalk(self):return"This animal is walking"classDog(Animal):# Inherits from Animaldefmake_sound(self):return"Woof! Woof!"# New method in Dog classdog = Dog()print(dog.walk())# Inherited method from Animal classprint(dog.make_sound())# Method defined in Dog class
The Dog
class inherits the walk()
method from the Animal
class and defines its own make_sound()
method, demonstrating inheritance.
Multiple inheritance
In multiple inheritance, a child class inherits from more than one parent class, meaning it gains attributes and behaviors from multiple sources.
An example demonstrating this is:
classFlyer:deffly(self):return"I can fly!"classSwimmer:defswim(self):return"I can swim!"classDuck(Flyer, Swimmer):passduck = Duck()print(duck.fly())# Inherited from Flyerprint(duck.swim())# Inherited from Swimmer
The Duck
class inherits both fly()
and swim()
without defining new methods.
But what happens if both parent classes have the same method? In multiple inheritance, if a method exists in both parent classes, Python looks at the order in which the parent classes are listed when defining the child class. It starts with the first parent (leftmost) and moves to the next until it finds the method. This order is determined by the Method Resolution Order (MRO).
Multilevel inheritance
Multilevel inheritance follows a chain-like structure where a class inherits from another class, which in turn inherits from another. This creates a hierarchy where lower-level classes gain features from all their ancestors, making code reuse efficient.
An example showcasing multilevel inheritance is:
classGrandparent:defwisdom(self):return"Experience matters."classParent(Grandparent):defadvice(self):return"Plan for the future."classChild(Parent):deffun(self):return"Live in the moment!"kid = Child()print(kid.wisdom())# From Grandparentprint(kid.advice())# From Parentprint(kid.fun())# From Child
The Child
class inherits from Parent
class, which itself inherits from the Grandparent
class.
Hierarchical inheritance
In hierarchical inheritance a single parent class has multiple child classes, each inheriting common features from the parent but also having their own specialized functionalities.
Here’s an example of the implementation of hierarchical inheritance:
classVehicle:defstart(self):return"Engine starting..."classCar(Vehicle):defdrive(self):return"Driving a car."classMotorcycle(Vehicle):defride(self):return"Riding a motorcycle."car = Car()bike = Motorcycle()print(car.start())# Inherited from Vehicleprint(car.drive())print(bike.start())# Inherited from Vehicleprint(bike.ride())
Both Car
and Motorcycle
inherit from Vehicle
but add their own behaviors.
Hybrid inheritance
Hybrid inheritance is a combination of multiple inheritance types in a single program, forming a complex hierarchy.
An example to understand the working of hybrid inheritance is:
classEngine:defstart_engine(self):return"Engine started."classWheels:defroll(self):return"Wheels rolling."classCar(Engine, Wheels):defdrive(self):return"Car is moving."classElectricCar(Car):defcharge_battery(self):return"Charging battery."tesla = ElectricCar()print(tesla.start_engine())# Inherited from Engineprint(tesla.roll())# Inherited from Wheelsprint(tesla.drive())# Inherited from Carprint(tesla.charge_battery())# Own method
ElectricCar
inherits from Car
, which itself inherits from both Engine
and Wheels
.
Inheritance is useful, but sometimes we need better control over parent methods. That’s where the super()
function helps. Let’s see how it works.
What is the super()
function in Python
Inheritance allows child classes to reuse and extend the functionality of parent classes, but sometimes, we need a way to access the parent’s methods directly. Python’s super()
function calls methods from a parent class within a child class. It ensures that the parent’s methods are executed without needing to reference the parent’s name explicitly.
The advantages of super()
function are:
- It helps in reusing parent class methods without rewriting code.
- It supports multiple inheritance by properly managing method resolution order (MRO).
- It makes code more maintainable and scalable.
Here’s an example to understand the super()
function:
Let’s say we’re building a Coffee Shop Ordering System where different types of coffee inherit from a base class:
classCoffee:def__init__(self, size):self.size = sizedefdescribe(self):returnf"{self.size} coffee"classEspresso(Coffee):def__init__(self, size, shots):super().__init__(size)# Call parent class constructorself.shots = shotsdefdescribe(self):returnf"{super().describe()} with {self.shots} extra shots of espresso"order = Espresso("Large",2)print(order.describe())# Output: Large coffee with 2 extra shots of espresso
In this code:
- The
Coffee
class defines a basic coffee with a size. - The
Espresso
class inherits fromCoffee
and adds an extra feature: espresso shots. super().__init__(size)
calls the parent class’s__init__
method, ensuringsize
is set.super().describe()
fetches theparent’s describe()
method and extends it.
That is how the super()
function makes inheritance more efficient by reusing parent class methods cleanly.
Advantages and limitations of inheritance
Inheritance helps structure code efficiently, but it also comes with challenges that developers should be aware of. Here is a list explaining them:
Advantages | Limitations |
---|---|
Parent class methods and attributes can be reused in multiple child classes, reducing redundancy. | Deep inheritance chains can make code harder to debug and maintain. |
New features can be added to child classes without modifying the parent class, making it easier to scale. | Child classes are tightly coupled to parent classes, making updates risky. |
Helps structure code hierarchically, improving readability and debugging. | Multiple inheritance can lead to method resolution order (MRO) conflicts. |
Groups related functionalities, improving maintainability and modularity. | In some cases, using composition instead of inheritance provides more flexibility. |
Conclusion
Inheritance helps in code reuse and organization by allowing child classes to derive properties from parent classes. In this article, we explored its types - single, multiple, multilevel, hierarchical, and hybrid, along with the super()
function and its pros and cons. While inheritance is powerful, it should be used wisely to maintain code clarity.
To learn more about object-oriented programming in Python, check out the Learn Intermediate Python 3 course at Codecademy!
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
Understanding Polymorphism in Python (With Examples)
Learn how to implement polymorphism in Python with practical examples and applications. Master this essential OOP concept to write more flexible, reusable code for your projects. - Article
Scope in Java
Explore the concept of scope in Java, including class level, method level, and block scope. Learn about access modifiers, instance variables, method overloading, and more. - Article
How to use Generative AI for Unit Testing
Learn how to use ChatGPT and generative AI for unit testing in Python code. This guide covers basic and edge case testing, ensuring your code performs reliably.
Learn more on Codecademy
- Free course
Learn Java: Inheritance and Polymorphism
Learn how to go further with classes by using inheritance and polymorphism.Beginner Friendly2 hours - Free course
Learn C#: Classes, Objects, Interfaces, and Inheritance
Explore C# subclasses, classes, superclasses, and more in this introduction to object-oriented programming with C#.Beginner Friendly8 hours - Free course
Learn Java: Classes, Methods, Inheritance, and Polymorphism
Take a deeper look into Java classes and methods and learn the basics of encapsulation.Beginner Friendly4 hours