Python Inheritance Tutorial – Complete Guide

In the realm of coding, understanding inheritance in Python is a bit like understanding the DNA of a codebase where attributes and behavior are inherited from parent to offspring, just like in biological genetics. This concept is a core part of Python and programming in general, fostering efficient code reuse and a clean, structured project layout. We invite you to dive in and discover the power of inheritance in Python in this compelling and informative tutorial.

What Is Inheritance in Python?

Inheritance in Python is a method for forming new classes using already defined classes. The newly formed classes are called derived classes or child classes, and the classes that we derive from are base classes or parent classes.

Why Is It Important?

Inheritance is a cornerstone feature of Object Oriented Programming (OOP) which Python supports. It allows us to build on previous work without having to build our classes from scratch every time. This contributes to the efficient use of code and proper organization, making our programs easier to write, read, and maintain.

When to Use Python Inheritance?

Python inheritance is widely used when you want to create a new class, and there is already a class that includes some of the code that you want to use. It helps to provide the hierarchical classification. Because it’s a real-world phenomenon, you can find inheritance being used in developing applications involving genetics, commerce, games, and more.

CTA Small Image

FREE COURSES AT ZENVA

LEARN GAME DEVELOPMENT, PYTHON AND MORE

AVAILABLE FOR A LIMITED TIME ONLY

Python Inheritance: The Basics

Let’s start by creating a simple parent class:

class Animal:
    def __init__(self, name):
        self.name = name
        
    def speak(self):
        pass

The parent class “Animal” has an initialization method which sets the name attribute, and a “speak” method which does not have any implementation. We can create child classes from this parent class that have additional attributes and methods.

class Dog(Animal):
    def speak(self):
        return self.name + ' says Woof!'
    
class Cat(Animal):
    def speak(self):
        return self.name + ' says Meow!'

In the above code, we have two child classes: Dog and Cat, both inheriting from the parent class Animal. Both Dog and Cat classes have a “speak” method that overrides the “speak” method in the parent class.

Using the Child Classes

Now we can use the Dog and Cat classes to create dog and cat objects:

fido = Dog('Fido')
isis = Cat('Isis')

print(fido.speak())  # Outputs: Fido says Woof!
print(isis.speak())  # Outputs: Isis says Meow!

Understanding Single Inheritance

Now let’s observe how Python implements single inheritance which is termed as when a child class inherits only from one parent class. Here, the child class inherits both the attributes and behaviors of the parent class, and it can also introduce new ones:

class Bird(Animal):
    def __init__(self, name, can_fly):
        super().__init__(name)
        self.can_fly = can_fly

    def fly_info(self):
        return self.name + ' can fly: ' + str(self.can_fly)

parrot = Bird('Parrot', True)

print(parrot.fly_info())  # Outputs: Parrot can fly: True

In the above example, the Bird class inherits from the Animal parent class and adds a new attribute “can_fly”. It also adds a new method “fly_info” that provides information about whether the bird can fly.

Understanding Multiple Inheritance

Python also supports multiple inheritance, a scenario where a class can inherit from more than one parent class. This can be achieved simply by adding more parent classes to the class definition.

class RunningAnimal(Animal):  
    def run(self):
        return self.name + ' can run!'

class Bat(Bird, RunningAnimal):
    pass

bat = Bat('Bat', False)
print(bat.fly_info())  # Outputs: Bat can fly: False
print(bat.run())  # Outputs: Bat can run!

In the above example, Bat inherits from both Bird and RunningAnimal, gaining the attributes and behaviors of both parent classes.

Understanding Polymorphism

Polymorphism is another fundamental concept in OOP, occurring when each child class has methods that are unique to itself, even providing different implementations for a method that is already defined in its parent class.

class Elephant(Animal):
    def speak(self):
        return self.name + ' makes a trumpet sound!'

class Mouse(Animal):
    def speak(self):
        return self.name + ' squeaks!'

dumbo = Elephant('Dumbo')
jerry = Mouse('Jerry')

for animal in (dumbo, jerry):
    print(animal.speak())

In the above example, the Elephant and Mouse classes both redefine the “speak” method of the parent class Animal, thereby providing their own unique responses.

Understanding Function Overloading

Overloading is also a part of Python’s inheritance feature where a class method’s behavior changes based on its parameters. Even though Python doesn’t support function overloading directly, we can achieve the similar effect using keyword arguments.

class Employee:
    def bonus(self, base, percentage = 0.1):
        return base * percentage

class Manager(Employee):
    def bonus(self, base, percentage = 0.2):
        return base * percentage    

e = Employee()
m = Manager()

print(e.bonus(1000))  # Outputs: 100.0
print(m.bonus(1000))  # Outputs: 200.0

In the above code, the “bonus” method in the Manager class has a different percentage than the Employee class, thus the Manager’s bonus is different than the Employee’s bonus.

Understanding The super() Function

The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object of the superclass which then allows you to call that superclass’s methods.

class Horse(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed

    def horse_info(self):
        return self.name + ' is a ' + self.breed
        
whirlaway = Horse('Whirlaway', 'Thoroughbred')
print(whirlaway.horse_info())  # Outputs: Whirlaway is a Thoroughbred

Here, we’ve used the super() function to call the __init__ method of the Animal superclass, enabling us to use its name attribute as well as add a new attribute, breed, for our Horse class.

Operator Overloading

Operator overloading allows you to redefine the way an operator works when used with objects of a class. Here is a simple example of operator overloading with the “+” operator.

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return f"({self.x}, {self.y})"

    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        return Point(x, y)

p1 = Point(1,2)
p2 = Point(3,4)
print(p1 + p2)  # Outputs: (4, 6)

In the code above, we redefine the “+” operator to add the respective attributes of two Point objects and return a new Point object.

Where to Go Next?

By now you should have a solid understanding of Python inheritance and how it enables efficient and organized coding. But don’t stop here! Python is a vast language with many more concepts to explore and master. Let’s pump up your Python prowess to the next level.

The Python Mini-Degree

For those looking to dive deeper into Python, we highly recommend our Python Mini-Degree. This comprehensive collection of Python courses is carefully curated to guide you from beginner to advanced programming skills. The curriculum includes coding basics, algorithms, object-oriented programming, game development, and app development, with a strong focus on practical learning.

Python is a versatile and robust language, used extensively in industries like data science, machine learning, and space exploration. With our Python Mini-Degree, you’ll learn Python programming by creating your very own games, algorithms, and real-world apps. Our courses are flexible, available 24/7, and practice coding right in the browser. Upon course completion, you’ll get certificates to boost your resume.

Many of our students have used skills they’ve learned from Zenva Academy to publish their own games, land jobs, and even start businesses. Jumpstart your Python journey with Zenva and start creating today!

Intermediate-Level Python Courses

For learners who have already grasped Python basics and want to delve into more advanced topics and projects, make sure to check out our intermediate-level Python courses.

At Zenva, we aim to cultivate a comprehensive learning environment for all skill levels. From beginner to professional, we provide a range of over 250 supported courses to boost your career. Learn coding, create games, and earn certificates with Zenva. Your continuous learning journey starts here.

Conclusion

Congratulations! You’ve navigated the complexities of Python inheritance, a pivotal building block in your journey to master Python. As you venture forward, remember that everyday offers a new opportunity to learn and improve. Keep practicing and don’t hesitate to revisit topics for clarity. The more you learn the more possible it becomes to create incredible, functional programs and applications.

We can’t stress enough how helpful our Python Mini-Degree can be for all Python learners. As you acquire new knowledge, apply it immediately with our hands-on projects and interactivity. Python’s world is diverse and limitless, from game design to machine learning, and we are thrilled to accompany you on this fascinating journey. Let’s keep coding, exploring, and innovating with Zenva Academy!

FREE COURSES

Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Unreal, Python, Godot and more.