Inheritance (การสืบทอด) เป็นแนวคิดที่คลาสหนึ่งเข้าถึงเมธอดและพรอพเพอร์ตี้ของอีกคลาสหนึ่งได้
- Parent Class คือคลาสที่ถูกสืบทอด เรียกอีกอย่างว่า Base Class
- Child Class คือคลาสที่สืบทอดมาจากอีกคลาส เรียกอีกอย่างว่า Derived Class
ใน Python มี Inheritance 2 ประเภทหลัก:
- Multiple Inheritance (การสืบทอดหลายทาง)
- Multilevel Inheritance (การสืบทอดหลายระดับ)
Multiple Inheritance
Child Class หนึ่งสืบทอดจาก Parent Class หลายตัว
ตัวอย่าง
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
Multilevel Inheritance
ในประเภทนี้ คลาสหนึ่งสามารถสืบทอดจาก Child Class / Derived 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
นอกจากนี้ Python ยังรองรับ Hierarchical Inheritance (หนึ่ง Parent หลาย Child) และ Hybrid Inheritance (ผสมผสานหลายประเภท)