How to create a new Python class that inherits from an existing class

PythonPythonBeginner
Practice Now

Introduction

In this tutorial, we will explore the concept of class inheritance in Python programming. You will learn how to create a new class that inherits from an existing class, allowing you to reuse and extend the functionality of the parent class.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python/ObjectOrientedProgrammingGroup -.-> python/inheritance("`Inheritance`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") subgraph Lab Skills python/inheritance -.-> lab-398167{{"`How to create a new Python class that inherits from an existing class`"}} python/classes_objects -.-> lab-398167{{"`How to create a new Python class that inherits from an existing class`"}} python/constructor -.-> lab-398167{{"`How to create a new Python class that inherits from an existing class`"}} python/polymorphism -.-> lab-398167{{"`How to create a new Python class that inherits from an existing class`"}} python/encapsulation -.-> lab-398167{{"`How to create a new Python class that inherits from an existing class`"}} end

Introduction to Class Inheritance

In Python, inheritance is a fundamental concept that allows you to create a new class based on an existing one. The new class, known as the derived or child class, inherits the attributes and methods from the existing class, known as the base or parent class. This allows you to reuse and extend the functionality of the parent class, making your code more efficient and maintainable.

Inheritance is particularly useful when you have a group of related classes that share common characteristics and behaviors. By creating a base class that encapsulates these shared elements, you can then derive specialized classes from it, each with its own unique features and functionality.

One of the key benefits of inheritance is the ability to override and extend the inherited functionality. This means that you can modify or add to the behavior of the parent class in the child class, allowing you to tailor the functionality to your specific needs.

## Example of a base class
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print("The animal makes a sound.")

## Example of a derived class
class Dog(Animal):
    def speak(self):
        print("The dog barks.")

In the example above, the Dog class inherits from the Animal class, and it overrides the speak() method to provide a more specific implementation for a dog.

By understanding the concepts of class inheritance, you can create more modular, flexible, and maintainable Python code that takes advantage of code reuse and polymorphism.

Creating a Derived Class

To create a derived class in Python, you use the following syntax:

class DerivedClassName(BaseClassName):
    ## class definition
    pass

In this syntax, DerivedClassName is the name of the new class you are creating, and BaseClassName is the name of the existing class that you want to inherit from.

Here's an example:

## Base class
class Vehicle:
    def __init__(self, make, model):
        self.make = make
        self.model = model

    def start(self):
        print("The vehicle is starting.")

## Derived class
class Car(Vehicle):
    def __init__(self, make, model, num_doors):
        super().__init__(make, model)
        self.num_doors = num_doors

    def start(self):
        print("The car is starting.")

## Create an instance of the derived class
my_car = Car("Toyota", "Camry", 4)
my_car.start()  ## Output: The car is starting.

In this example, the Car class inherits from the Vehicle class. The Car class has its own __init__() method, which calls the __init__() method of the Vehicle class using the super() function. The Car class also overrides the start() method of the Vehicle class.

By creating a derived class, you can take advantage of the existing functionality of the base class and add or modify it to suit your specific needs.

classDiagram class Vehicle { +make: str +model: str +start() } class Car { +num_doors: int +start() } Vehicle <|-- Car

The diagram above illustrates the inheritance relationship between the Vehicle and Car classes.

Overriding and Extending Inherited Functionality

One of the key benefits of inheritance in Python is the ability to override and extend the inherited functionality. This means that you can modify or add to the behavior of the parent class in the child class, allowing you to tailor the functionality to your specific needs.

Overriding Inherited Methods

To override an inherited method, you simply define a method in the child class with the same name as the method in the parent class. When you call the method on an instance of the child class, the child class's implementation will be used instead of the parent class's implementation.

## Base class
class Animal:
    def speak(self):
        print("The animal makes a sound.")

## Derived class
class Dog(Animal):
    def speak(self):
        print("The dog barks.")

## Create an instance of the derived class
my_dog = Dog()
my_dog.speak()  ## Output: The dog barks.

In this example, the Dog class overrides the speak() method of the Animal class, providing a more specific implementation for a dog.

Extending Inherited Functionality

In addition to overriding inherited methods, you can also extend the functionality of the parent class by adding new methods or attributes to the child class.

## Base class
class Vehicle:
    def __init__(self, make, model):
        self.make = make
        self.model = model

    def start(self):
        print("The vehicle is starting.")

## Derived class
class ElectricCar(Vehicle):
    def __init__(self, make, model, battery_capacity):
        super().__init__(make, model)
        self.battery_capacity = battery_capacity

    def start(self):
        print("The electric car is starting.")

    def charge(self):
        print("The electric car is charging.")

## Create an instance of the derived class
my_electric_car = ElectricCar("Tesla", "Model S", 100)
my_electric_car.start()  ## Output: The electric car is starting.
my_electric_car.charge()  ## Output: The electric car is charging.

In this example, the ElectricCar class extends the Vehicle class by adding a battery_capacity attribute and a charge() method, while also overriding the start() method.

By understanding how to override and extend inherited functionality, you can create more flexible and powerful Python classes that meet your specific requirements.

Summary

By the end of this tutorial, you will have a solid understanding of how to create a new Python class that inherits from an existing class. You will be able to leverage the power of class inheritance to write more efficient and maintainable code, as well as override and extend the functionality of the parent class to suit your specific needs.

Other Python Tutorials you may like