Python Inheritance

🐍 Python Inheritance

Inheritance is a core concept of Object-Oriented Programming (OOP).
It allows a class (child) to inherit attributes and methods from another class (parent).


 1️⃣ Why Use Inheritance?

  • Reusability: Avoid rewriting code.

  • Extensibility: Add new features to existing classes.

  • Hierarchy: Represents real-world relationships (e.g., Vehicle → Car → ElectricCar).


 2️⃣ Basic Syntax


 

The Child class automatically inherits the greet() method from Parent.


 3️⃣ Example: Single Inheritance


 


 4️⃣ Using super() to Call Parent Constructor


 


 5️⃣ Multiple Inheritance

A child class can inherit from more than one parent.


 

Python uses Method Resolution Order (MRO) to determine which parent method to use.


 6️⃣ Multilevel Inheritance


 


 7️⃣ Hierarchical Inheritance

Multiple child classes inherit from one parent class.


 


 8️⃣ Overriding Parent Methods

Child can override parent method:


 

Output:

Some sound
Woof! Woof!

 9️⃣ Summary Table

Type of InheritanceExample
SingleChild inherits from one parent
MultipleChild inherits from multiple parents
MultilevelGrandparent → Parent → Child
HierarchicalOne parent → multiple children
HybridCombination of multiple types

 10️⃣ Example: Real-Life Use


 


Inheritance makes code reusable, organized, and scalable.

You may also like...