Inheritance ও Polymorphism
🧬 Python Inheritance ও Polymorphism (সম্পূর্ণ গাইড)
Python এর Object-Oriented Programming (OOP) এর দুটি সবচেয়ে গুরুত্বপূর্ণ ধারণা হলো Inheritance এবং Polymorphism। এগুলো ব্যবহার করে আমরা কোডকে আরও reusable, scalable এবং maintainable করতে পারি।
📌 Inheritance কী?
Inheritance হলো এমন একটি প্রক্রিয়া যেখানে একটি class (Child) অন্য একটি class (Parent) এর property ও method ব্যবহার করতে পারে।
🔹 কেন Inheritance ব্যবহার করবেন?
- Code reuse করা যায়
- Duplicate code কমে
- Project structure পরিষ্কার হয়
- Maintenance সহজ হয়
🧪 Inheritance Example
class Animal:
def speak(self):
print("Animal can make sound")
class Dog(Animal):
def bark(self):
print("Dog is barking")
dog = Dog()
dog.speak()
dog.bark()
📤 Output:
Animal can make sound
Dog is barking
📌 Python এ Inheritance এর প্রকারভেদ
- Single Inheritance
- Multilevel Inheritance
- Multiple Inheritance
- Hierarchical Inheritance
🔹 Multilevel Inheritance Example
class Vehicle:
def start(self):
print("Vehicle started")
class Car(Vehicle):
def drive(self):
print("Car is driving")
class ElectricCar(Car):
def charge(self):
print("Electric car is charging")
ecar = ElectricCar()
ecar.start()
ecar.drive()
ecar.charge()
📤 Output:
Vehicle started
Car is driving
Electric car is charging
🔁 Polymorphism কী?
Polymorphism মানে হলো “একই method নাম, কিন্তু ভিন্ন ভিন্ন আচরণ”। একই function বা method বিভিন্ন class এ ভিন্নভাবে কাজ করতে পারে।
🔹 Polymorphism এর সুবিধা
- Flexible code লেখা যায়
- Code readability বাড়ে
- Large project handle সহজ হয়
🧪 Polymorphism Example (Method Overriding)
class Bird:
def fly(self):
print("Bird can fly")
class Sparrow(Bird):
def fly(self):
print("Sparrow flies low")
class Eagle(Bird):
def fly(self):
print("Eagle flies high")
birds = [Sparrow(), Eagle()]
for bird in birds:
bird.fly()
📤 Output:
Sparrow flies low
Eagle flies high
🦆 Duck Typing (Python Special Polymorphism)
Python এ class type গুরুত্বপূর্ণ নয়, method থাকলেই চলবে — একে বলা হয় Duck Typing।
class Laptop:
def work(self):
print("Coding on laptop")
class Mobile:
def work(self):
print("Coding on mobile")
def do_work(device):
device.work()
do_work(Laptop())
do_work(Mobile())
📤 Output:
Coding on laptop
Coding on mobile
✨ সংক্ষেপে (Summary)
- Inheritance = Parent থেকে Child এ feature নেওয়া
- Polymorphism = একই method, ভিন্ন আচরণ
- Method overriding Polymorphism এর মূল ভিত্তি
- Duck Typing Python কে আরও powerful করে
লোড হচ্ছে...
1. Inheritance কী?
একটি class অন্য class এর বৈশিষ্ট্য গ্রহণ করে।
2. Polymorphism কী?
একই নামের method ভিন্নভাবে কাজ করে।
3. Inheritance এর সুবিধা কী?
Code reuse হয়।