ก่อนจะไปอธิบาย super() ก่อนอื่นเราต้องรู้เกี่ยวกับมรดกหลายส่วน แนวความคิด
มรดกหลายรายการ :หมายถึงคลาสลูกหนึ่งคลาสสามารถสืบทอดคลาสพาเรนต์ได้หลายคลาส
ในตัวอย่างต่อไปนี้ คลาสลูกสืบทอดวิธีการแอตทริบิวต์จากคลาสหลัก
ตัวอย่าง
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( ) ใช้งานได้หลายมรดก
สุดยอด() :สามารถใช้ super function เพื่อแทนที่การเรียกแบบชัดแจ้งเป็น
ตัวอย่าง
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__()
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