ตัวอย่างการใช้งาน ฟังก์ชั่น super ใน กาเรขียน Python แบบ OOP
ตัวอย่าง สร้าง class มา สาม class
class Base(object):
def __init__(self):
print ("Base created")
def fa(self):
print ('Value in methode FA')
class ChildA(Base):
def __init__(self):
Base.__init__(self)
Base.fa(self)
class ChildB(Base):
def __init__(self):
super(ChildB, self).__init__()
super(ChildB, self).fa()
print (ChildA(), ChildB())
ผลที่ได้
Base created
Value in methode FA
Base created
Value in methode FA
คำอธิบาย
การใช้งาน super เป็น การเรียกใช้งาน method ของ class แม่ โดยคลาสลูกต้องสืบทอดจากคลาสแม่เท่านั้นถึงจะเรียนใช้งาน ด้วย method ของ คลาสแม่ได้
นอกจาก การใช้ ฟังก์ชั่น super แล้วเรายังสามารถ ใช้ คำว่า ชื่อคลาสแม่ตรงๆ เลยก็ได้