Inheritance in Python

  • Last updated Apr 25, 2024

In Python, inheritance is a mechanism for inheriting attributes and methods from one class to another. Inheritance is used when we want a new class to inherit attributes and methods from an existing class. Inheritance is a fundamental concept in object-oriented programming (OOP).

A class from which properties and methods are inherited to another class is called a Parent class. A class which inherits properties and methods from a Parent class is called its Child class.

Example of Inheritance:

# Parent class
class Animal:
    def __init__(self, name, color, age):
        self.name = name
        self.color =  color
        self.age = age

    def eat(self):
        print("Animal is eating.")
        # Logic here

# Child class
class Dog(Animal):
    def __init__(self, name, color, age, weight):
        super().__init__(name,color, age)
        self.weight = weight

    def bark(self):
        return f"{self.name} is a barking."

# Child class
class Cat(Animal):
    def __init__(self, name, color, age, weight):
        super().__init__(name,color, age)
        self.weight = weight

    def meow(self):
        return f"{self.name} is a meowing."

#Creating Objects
dog = Dog("Dog", "brown", 5, 15)
cat = Cat("Cat", "white", 2, 3)
# Accessing attributes
print(dog.name)
print(dog.color)
print(dog.age)
print(dog.bark())
print()
print(cat.name)
print(cat.color)
print(cat.age)
print(cat.meow())

The output of the above code is as follows:

Dog
brown
5
Dog is a barking.

Cat
white
2
Cat is a meowing.