ইনহেরিটেন্স (Inheritance) হল একটি কনসেপ্ট যেখানে একটি ক্লাস অন্য ক্লাসের মেথড ও প্রপার্টি অ্যাক্সেস করতে পারে।
- প্যারেন্ট ক্লাস হল যে ক্লাস থেকে ইনহেরিট করা হয়, এটাকে বেস ক্লাসও বলা হয়।
- চাইল্ড ক্লাস হল যে ক্লাস অন্য ক্লাস থেকে ইনহেরিট করে, এটাকে ডেরাইভড ক্লাসও বলা হয়।
পাইথনে ইনহেরিটেন্স মূলত দুই প্রকার:
- মাল্টিপল ইনহেরিটেন্স (Multiple Inheritance)
- মাল্টিলেভেল ইনহেরিটেন্স (Multilevel Inheritance)
মাল্টিপল ইনহেরিটেন্স
মাল্টিপল ইনহেরিটেন্সে একটি চাইল্ড ক্লাস একাধিক প্যারেন্ট ক্লাস থেকে ইনহেরিট করতে পারে।
উদাহরণ
class Father:
fathername = ""
def father(self):
print(self.fathername)
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
class Daughter(Father, Mother):
def parent(self):
print("Father:", self.fathername)
print("Mother:", self.mothername)
s1 = Daughter()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent()
আউটপুট
Father: Srinivas Mother: Anjali
মাল্টিলেভেল ইনহেরিটেন্স
এই ধরনের ইনহেরিটেন্সে একটি ক্লাস চাইল্ড ক্লাস/ডেরাইভড ক্লাস থেকে ইনহেরিট করতে পারে।
উদাহরণ
# Daughter ক্লাস Father এবং Mother ক্লাস থেকে ইনহেরিট করেছে,
# যেগুলো আবার Family ক্লাস থেকে ডেরাইভড।
class Family:
def family(self):
print("This is My family:")
class Father(Family):
fathername = ""
def father(self):
print(self.fathername)
class Mother(Family):
mothername = ""
def mother(self):
print(self.mothername)
class Daughter(Father, Mother):
def parent(self):
print("Father:", self.fathername)
print("Mother:", self.mothername)
s1 = Daughter()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.family()
s1.parent()
আউটপুট
This is My family: Father: Srinivas Mother: Anjali