ผลต่างระหว่างรุ่นของ "Python Programming/Inheritance"
ไปยังการนำทาง
ไปยังการค้นหา
Cardcaptor (คุย | มีส่วนร่วม) |
Cardcaptor (คุย | มีส่วนร่วม) |
||
| แถว 21: | แถว 21: | ||
>>> a.say_age() # สังเกตว่าเมท็อดนี้ถูกเปลี่ยนแปลงในคลาส Superdog | >>> a.say_age() # สังเกตว่าเมท็อดนี้ถูกเปลี่ยนแปลงในคลาส Superdog | ||
I am not telling you | I am not telling you | ||
| + | </pre> | ||
| + | |||
| + | == ความเป็นพลวัต == | ||
| + | เรานิยามคลาส Plane และคลาส Fly เพิ่มดังนี้ | ||
| + | |||
| + | <pre title="interpreter"> | ||
| + | >>> 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" | ||
</pre> | </pre> | ||
รุ่นแก้ไขเมื่อ 18:40, 19 ตุลาคม 2551
- ส่วนนี้ลอกมาจาก การโปรแกรมเชิงวัตถุในไพทอน ของ จิตรทัศน์ ฝักเจริญผล
เราสามารถสร้างคลาส 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"