Inheritance in Python


Python - Inheritance

In Python, inheritance is a way to create a new class that is a modified version of an existing class. Inheritance allows you to customise or extend the behavior of the class for your specific needs.

The existing class is called base class, parent class, or super class.

The new class is called extended class, child class, or sub class.

Syntax

The syntax for a class B to inherit a parent class A is

class A:
    pass

class B(A):
    pass

Please observe the syntax: ChildClassName(ParentClassName).

Example

In this example, we define three classes: Animal, Dog, and Cat.

Animal is parent class.

Dog and Cat are child classes of Animal class.

The object of Dog and Cat classes can access the properties and methods of the Animal class.

Python Program

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

    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")
    
    def run(self):
        print(self.name, "is running.")

class Dog(Animal):
    def speak(self):
        print(self.name, "says Woof Woof!")

class Cat(Animal):
    def speak(self):
        print(self.name, "says Meow Meow!")

dog = Dog("Pigo")
cat = Cat("Keto")

dog.speak()
dog.run()

cat.speak()
cat.run()

Output

Pigo says Woof Woof!
Pigo is running.
Keto says Meow Meow!
Keto is running.

Now, let us discuss the example in detail.

  • The parent class Animal has a property name, an abstract method speak(), and a method run().
  • The child classes Dog, and Cat, that inherited Animal class, have access to the name property, and the methods speak() and run() of the Animal class.
  • The two child classes have overridden the speak() method of parent class. When speak() method is called on any of the objects of child classes, then the method defined in the respective child classes is executed. The line dog.speak() executes the method in the child class Dog.
  • dog.run() executes the method in parent class Animal, because the child class object can access the method in parent class Animal, and there is no run() method in the child class Dog.

Uses of Inheritance

Inheritance allows you to create classes that build upon the functionality of existing classes, while also providing the flexibility to customize or modify that functionality as needed.

By using inheritance, you can avoid duplicating code and make your code more modular and maintainable.

Summary

In this Python Classes and Objects tutorial, we learned about Inheritance in Python, and how to implement inheritance with classes, with the help of an example.