📦 Inheritance in Python
Reusing Code with Parent and Child Classes
🔹 DefinitionInheritance in Python is an object-oriented programming concept where one class acquires the properties and methods of another class. In simple words, inheritance allows a new class to reuse existing code instead of writing everything again.
The existing class is called the parent (or base) class, and the new class is called the child (or derived) class. Inheritance makes programs more organized, reduces duplication, and improves maintainability.
📌 Basic Syntax of Inheritance
class ParentClass:
# parent class code
pass
class ChildClass(ParentClass):
# child class code
pass
📂 Types of Inheritance in Python
Python supports five main types of inheritance.
1️⃣ Single Inheritance
DefinitionSingle inheritance means one child class inherits from one parent class.
Example
class Animal:
def sound(self):
print("Animals make sound")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
d.sound()
d.bark()
Here, Dog inherits from Animal. The Dog class can use both its own method and the parent’s method.
2️⃣ Multiple Inheritance
DefinitionMultiple inheritance means one child class inherits from more than one parent class.
Example
class Father:
def skill1(self):
print("Driving")
class Mother:
def skill2(self):
print("Cooking")
class Child(Father, Mother):
pass
c = Child()
c.skill1()
c.skill2()
The Child class gets features from both Father and Mother.
3️⃣ Multilevel Inheritance
DefinitionMultilevel inheritance means a class is derived from another derived class.
Example
class Grandparent:
def show1(self):
print("Grandparent")
class Parent(Grandparent):
def show2(self):
print("Parent")
class Child(Parent):
def show3(self):
print("Child")
obj = Child()
obj.show1()
obj.show2()
obj.show3()
Inheritance flows in levels, like a family tree.
4️⃣ Hierarchical Inheritance
DefinitionHierarchical inheritance means multiple child classes inherit from the same parent class.
Example
class Vehicle:
def info(self):
print("This is a vehicle")
class Car(Vehicle):
pass
class Bike(Vehicle):
pass
c = Car()
b = Bike()
c.info()
b.info()
Both Car and Bike share the same parent but are different classes.
5️⃣ Hybrid Inheritance
DefinitionHybrid inheritance is a combination of two or more types of inheritance.
Example
class A:
def showA(self):
print("Class A")
class B(A):
def showB(self):
print("Class B")
class C(A):
def showC(self):
print("Class C")
class D(B, C):
def showD(self):
print("Class D")
obj = D()
obj.showA()
obj.showB()
obj.showC()
obj.showD()
Hybrid inheritance mixes multilevel and multiple inheritance.
📌 Conclusion
Inheritance is one of the most powerful features of Python. It promotes code reuse, better structure, and easy maintenance. Understanding its types helps in designing clean and efficient programs.
🔑 Key Points to Remember
- Inheritance allows code reuse
- Child classes inherit parent features
- Python supports five types of inheritance
- Improves maintainability and structure