Notes
Categories

Inheritance in Python [ English ]

< Prev Next >

Inheritance in Python

1. Introduction

Inheritance is one of the fundamental concepts of Object-Oriented Programming (OOP). It allows a class (called the child class) to inherit properties and methods from another class (called the parent class).

This helps in code reuse, reduces duplication, and makes programs easier to maintain.

2. Definition

Inheritance is:

The mechanism by which one class acquires the properties and behavior of another class.

3. Syntax of Inheritance

class ParentClass:
    # parent class code

class ChildClass(ParentClass):
    # child class code

4. Basic Example

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    pass

d = Dog()
d.speak()

Output

Animal speaks

Explanation

5. Types of Inheritance in Python

5.1 Single Inheritance

One child class inherits from one parent class.

class A:
    def show(self):
        print("Class A")

class B(A):
    pass

5.2 Multiple Inheritance

One child class inherits from multiple parent classes.

class A:
    def showA(self):
        print("Class A")

class B:
    def showB(self):
        print("Class B")

class C(A, B):
    pass

5.3 Multilevel Inheritance

A class inherits from a class, which itself inherits from another class.

class A:
    def showA(self):
        print("Class A")

class B(A):
    def showB(self):
        print("Class B")

class C(B):
    pass

5.4 Hierarchical Inheritance

Multiple child classes inherit from one parent class.

class A:
    def show(self):
        print("Class A")

class B(A):
    pass

class C(A):
    pass

5.5 Hybrid Inheritance

Combination of two or more types of inheritance.

6. Using super() Function

The super() function is used to call methods of the parent class.

class Animal:
    def __init__(self):
        print("Animal constructor")

class Dog(Animal):
    def __init__(self):
        super().__init__()
        print("Dog constructor")

d = Dog()

Output

Animal constructor
Dog constructor

7. Method Overriding in Inheritance

class Animal:
    def sound(self):
        print("Animal sound")

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

d = Dog()
d.sound()

8. Advantages of Inheritance

9. Important Points

10. Summary

< Prev Next >