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
Run Code

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()
Run Code

Output

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

Now, let us discuss the example in detail.

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.

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us