ก่อนอธิบาย super() เราต้องเข้าใจแนวคิด Multiple 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 Child(Father, Mother):
def parent(self):
print("Father:", self.fathername)
print("Mother:", self.mothername)
s1 = Child()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent()
ผลลัพธ์
Father: Srinivas Mother: Anjali
การใช้งาน super() กับ Multiple Inheritance
super(): ฟังก์ชัน super ใช้แทนการเรียก Parent Class โดยตรง ช่วยให้จัดการ Method Resolution Order (MRO) ได้ถูกต้อง
ตัวอย่าง
class Father:
fathername = ""
def father(self):
print(self.fathername)
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
class Child(Father, Mother):
def parent(self):
super().__init__() # เรียก __init__ ของ parent ตาม MRO
print("I am here")
print("Father:", self.fathername)
print("Mother:", self.mothername)
s1 = Child()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent()
ผลลัพธ์
I am here Father: Srinivas Mother: Anjali
ใน Python 3 super() ไม่ต้องระบุอาร์กิวเมนต์ จะทำงานตาม MRO (Method Resolution Order) อัตโนมัติ