ผลต่างระหว่างรุ่นของ "Python Programming/Inheritance"
ไปยังการนำทาง
ไปยังการค้นหา
Cardcaptor (คุย | มีส่วนร่วม) (สร้างหน้าใหม่: : ''ส่วนนี้ลอกมาจาก [http://garnet.cpe.ku.ac.th/~jtf/dm/?q=node/31 การโปรแกรมเชิงวัตถุใ...) |
Cardcaptor (คุย | มีส่วนร่วม) |
||
| แถว 3: | แถว 3: | ||
เราสามารถสร้างคลาส Superdog ที่สืบทอดมาจากคลาส Dog ได้ โดยเขียน | เราสามารถสร้างคลาส Superdog ที่สืบทอดมาจากคลาส Dog ได้ โดยเขียน | ||
| − | <pre title="interpreter | + | <pre title="interpreter"> |
| − | class Superdog(Dog): | + | >>> class Superdog(Dog): |
| − | def fly(self): | + | ... def fly(self): |
| − | print "weeew weeeeeew", self.name, "is flying..." | + | ... print "weeew weeeeeew", self.name, "is flying..." |
| − | + | ... def say_age(self): | |
| − | def say_age(self): | + | ... print "I am not telling you" |
| − | print "I am not telling you" | + | </pre> |
| + | |||
| + | ซึ่งสามารถเรียกใช้ได้ดังนี้ | ||
| + | |||
| + | <pre title="interpreter"> | ||
| + | >>> 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 | ||
</pre> | </pre> | ||
รุ่นแก้ไขเมื่อ 18:38, 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