Inheritance

Learn Python inheritance with examples. Understand single, multiple, multilevel, hierarchical, and hybrid inheritance in Python classes.

Loading...
Inheritance

Inheritance allows a class (child class) to inherit properties and methods from another class (parent class). This promotes code reuse and enhances modularity.

Example:

class Animal:
    def speak(self):
        print("Animal speaks")
 
class Dog(Animal): # Dog inherits from Animal
    def speak(self):
        print("Dog barks")
 
dog = Dog()
dog.speak()  # Output: Dog barks

Here, Dog inherits from Animal but overrides the speak() method.


Types of Inheritance

  1. Single Inheritance: A child class inherits from one parent class.
  2. Multiple Inheritance: A child class inherits from more than one parent class.
  3. Multilevel Inheritance: A class inherits from another derived class, creating a chain.
  4. Hierarchical Inheritance: Multiple classes inherit from a single parent class.
  5. Hybrid Inheritance: Combines two or more types of inheritance.

👉 Next tutorial: Python Polymorphism

Support my work!