Inheritence in Python Programming

In this tutorial, we will learn how to implement the concept of inheritence in Python programming language and we’ll also dive into the concepts of base classes and  derived classes.

Inheritence in Python

Inheritence is one of the core concepts in OOP(object-oriented programming) paradigm.Inheritance allows us create a new class(derived class) based on an existing class(base class). The derived class(child class) inherits all the attributes and methods from the base class(parent class), allowing for code reuse and creation of  hierarchial relationship between classes.

Syntax:

Class BaseClass:
    {Body}
Class DerivedClass(BaseClass):
    {Body}

Implementation of Inheritence in Python

To implement inheritence we need first create base class and derived class.Let us look into how to create the above classes.

Creating the base class:
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")

    def info(self):
        return f"{self.name} is a {self.species}."
Creating the derived class:
class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

    def play(self):
        return f"{self.name} is playing with a ball."

The Animal class is a base class that provides common attributes like name and species, and methods like  info and speak. The speak method is intended to be overridden by subclasses.
The Dog class inherits from Animal, implementing the speak method to return “Woof!” and adding a play method. This class extends the functionality of Animal to represent a specific type of animal, a dog.

Source code:
# Base class
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")

    def info(self):
        return f"{self.name} is a {self.species}."

# Derived class
class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

    def play(self):
        return f"{self.name} is playing with a ball."

# Creating instances of the derived class
dog1 = Dog("Buddy", "dog")
dog2 = Dog("Max", "dog")

# Using the methods
print(dog1.info())
print(dog1.speak())
print(dog1.play())
print()
print(dog2.info())
print(dog2.speak())
print(dog2.play())
Output:
Buddy is a dog.
Buddy says Woof! 
Buddy is playing with a ball. 
Max is a dog. 
Max says Woof! 
Max is playing with a ball.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top