Inheritance in Python

This article provides a tutorial on inheritance in Python, a fundamental concept in object-oriented programming.

Updated March 9, 2023

Hello future Python wizard, welcome to Python Help!

Today, we’re going to talk about inheritance, a powerful feature of object-oriented programming that allows us to create new classes by extending existing ones.

Inheritance allows us to reuse code and create classes that are more specialized than their parent classes. In Python, we can achieve inheritance through the use of the super() function and the class statement.

Let’s start with an example. Suppose we have a class called Animal that has a method called speak(). We want to create a new class called Dog that inherits from Animal, but also has its own bark() method.

Here’s what the implementation could look like:

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"
    
    def bark(self):
        return "Woof! Woof!"

Notice how we’ve defined the Dog class with the Animal class as its parent using the (Animal) syntax. By doing so, the Dog class inherits all of the methods and attributes of the Animal class, including the speak() method. We can then add our own bark() method to the Dog class.

Let’s test it out:

dog = Dog()
print(dog.speak()) # Output: Woof!
print(dog.bark()) # Output: Woof! Woof!

As expected, the Dog class can both speak() like an Animal and bark() like a dog.

Now, let’s take a look at another example. Suppose we have a class called Shape that has a method called area(). We want to create a new class called Rectangle that inherits from Shape, but also has its own perimeter() method.

Here’s what the implementation could look like:

class Shape:
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def area(self):
        return self.width * self.height
    
    def perimeter(self):
        return 2 * (self.width + self.height)

Notice how we’ve defined the Rectangle class with the Shape class as its parent. We’ve also overridden the area() method to calculate the area of a rectangle, and added our own perimeter() method.

Let’s test it out:

rectangle = Rectangle(10, 20)
print(rectangle.area()) # Output: 200
print(rectangle.perimeter()) # Output: 60

As expected, the Rectangle class can both calculate its area() like a Shape and its perimeter() like a rectangle.

In summary, inheritance is a powerful feature of object-oriented programming that allows us to create new classes by extending existing ones. By inheriting methods and attributes from parent classes, we can reuse code and create more specialized classes. In Python, we can achieve inheritance through the use of the super() function and the class statement.

Stay up to date on the latest in Coding Python with AI and Data Science

Intuit Mailchimp