class Demo:
def __init__(self, i):
self.i = i
def __str__(self):
return str(self.i)
def hello(self):
print("hello " + self.__str__())
class SubDemo1(Demo):
def __init__(self, i, j):
super().__init__(i)
self.j = j
def __str__(self):
return super().__str__() + str(self.j)
class SubDemo2(Demo):
def __init__(self, i, j):
super().__init__(i)
self.j = j
self.k = str(self.i) + str(self.j)
def __str__(self):
return self.k
a = SubDemo1(22, 33)
b = SubDemo2(44, "55")
a.hello()
b.hello()
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:poly01.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

SubDemo1 與 SubDemo2 繼承 (inherit) 自 Demo ,因此兩個子類別也都繼承了 hello() 方法 (method) ,雖然 SubDemo1 與 SubDemo2 所建立的物件各自是不同型態,然而由繼承關係兩種型態可通用 hello() 。
其他的例子如
d1 = "12345"
d2 = [1, 2, 3, 4, "5"]
print(d1.count("4"))
print(d2.count("4"))
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:poly02.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月執行結果如下

d1 為字串 (string) , d2 為串列 (list) ,兩者皆屬於序列 (sequence) 的複合資料型態 (compound data type) ,有通用的 count() 方法,可計算某元素 (element) 累計出現的次數。
多型的應用很多,例如串列中可接受不同型態的物件當元素,或是方法可用不同型態的參數等。
| 中英文術語對照 | |
|---|---|
| 多型 | polymorphism |
| 物件導向程式語言 | object-oriented programming language |
| 物件 | object |
| 繼承 | inherit |
| 方法 | method |
| 字串 | string |
| 串列 | list |
| 序列 | sequence |
| 複合資料型態 | compound data type |
| 元素 | element |
參考資料
http://docs.python.org/py3k/reference/datamodel.html
http://docs.python.org/py3k/library/stdtypes.html
http://docs.python.org/py3k/reference/datamodel.html
http://docs.python.org/py3k/library/stdtypes.html
沒有留言:
張貼留言