DEV Community

Cover image for Inheritance in Python
Karthick (k)
Karthick (k)

Posted on

Inheritance in Python

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class).

Here, a parent class Animal is created that has a method info(). Then a child class Dog is created that inherits from Animal and adds additional behaviour.

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

    def info(self):
        print("Animal name:", self.name)

class Dog(Animal):
    def sound(self):
        print(self.name, "barks")

d = Dog("Buddy")
# Inherited method
d.info()     
d.sound()
Enter fullscreen mode Exit fullscreen mode

Output

Animal name: Buddy
Buddy barks

Benefits Of Inheritance

Promotes code reusability by sharing attributes and methods across classes.
Models real-world hierarchies like Animal -> Dog or Person -> Employee.
Simplifies maintenance through centralised updates in parent classes.
Enables method overriding for customised subclass behaviour.
Supports scalable, extensible design using polymorphism.

Top comments (0)