Python Programming/Inheritance

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
ส่วนนี้ลอกมาจาก การโปรแกรมเชิงวัตถุในไพทอน ของ จิตรทัศน์ ฝักเจริญผล

เราสามารถสร้างคลาส Superdog ที่สืบทอดมาจากคลาส Dog ได้ โดยเขียน

>>> class Superdog(Dog):
...     def fly(self):
...         print "weeew weeeeeew", self.name, "is flying..."
...     def say_age(self):
...         print "I am not telling you"

ซึ่งสามารถเรียกใช้ได้ดังนี้

>>> a = Superdog('Mabin',1)
>>> a.fly()
weeew weeeeeew Mabin is flying...
>>> a.say_hello()                   # สังเกตว่าเมท็อดนี้สืบทอดมาจากคลาส Dog
Hello, my name is Mambo
>>> a.say_age()                     # สังเกตว่าเมท็อดนี้ถูกเปลี่ยนแปลงในคลาส Superdog
I am not telling you

ความเป็นพลวัต

เรานิยามคลาส Plane และคลาส Fly เพิ่มดังนี้

>>> class Plane:
...     def __init__(self, brand, model):
...         self.brand = brand
...         self.model = model
...     def fly(self):
...         print self.brand, self.model, "is flying FAST!"
... 
>>> class Fly:
...     def fly(self):
...         print "Time flies like an arrow"

สังเกตว่าทั้งสามคลาสที่เราได้นิยามมา คือ Superdog, Plane และ Fly มีเมท็อด fly เหมือนกันทั้งสิ้น เราสามารถนำวัตถุของคลาสทั้งสามมาใช้ได้ในทุกที่ที่เราต้องการเรียกใช้เมท็อด fly เช่นในตัวอย่างด้านล่างนี้

>>> o1 = Superdog('Johny',3)
>>> o2 = Plane('AirSuperJet','T1000')
>>> o3 = Fly()
>>> 
>>> objs = [o1,o2,o3]
>>> for o in objs:
...     o.fly()
... 
weeew weeeeeew Johny is flying...
AirSuperJet T1000 is flying FAST!
Time flies like an arrow

เราอาจะเขียนฟังก์ชัน flyflyfly ดังด้านล่าง

>>> def flyflyfly(x):
...     print "Preparing..."
...     x.fly()
...     x.fly()
...     x.fly()
...