การสืบทอด เป็นแนวคิดที่คลาสหนึ่งเข้าถึงเมธอดและคุณสมบัติของคลาสอื่น
- คลาสหลักคือคลาสที่สืบทอดมาจากคลาส หรือเรียกอีกอย่างว่าคลาสเบส
- คลาสลูกคือคลาสที่สืบทอดมาจากคลาสอื่น เรียกอีกอย่างว่าคลาสที่ได้รับ
การสืบทอดใน python มีสองประเภท -
- การสืบทอดหลายรายการ
- การสืบทอดหลายระดับ
มรดกหลายรายการ −
ในการสืบทอดหลายคลาสย่อยหนึ่งคลาสสามารถสืบทอดคลาสพาเรนต์ได้หลายคลาส
ตัวอย่าง
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 class inherited from Father and Mother classes which derived from Family class.
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