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
Childclass automatically inherits thegreet()method fromParent.
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:
9️⃣ Summary Table
| Type of Inheritance | Example |
|---|---|
| Single | Child inherits from one parent |
| Multiple | Child inherits from multiple parents |
| Multilevel | Grandparent → Parent → Child |
| Hierarchical | One parent → multiple children |
| Hybrid | Combination of multiple types |
10️⃣ Example: Real-Life Use
Inheritance makes code reusable, organized, and scalable.
