例如我們設計一個 Animal 類別,囊括所有我們想要有的動物特性,吃、喝、拉、撒、睡等等,我們另外設計一個 Dog 類別繼承 Animal ,可是「狗」還有些跟主人親密的寵物特性等等,這與一般動物的原始不太一樣。
當然,寵物特性可以全部規劃在 Dog 中,可是如果要另外設計 Cat 類別呢?因此,將所有寵物特性獨立成 Pet 類別,然後給 Dog 及 Cat 都繼承,使「狗」與「貓」都有動物特性,也都具有寵物特性。
多重繼承 (mutliple inheritance) 的使用很簡單,寫父類別的小括弧中,利用逗點分開每個父類別即可。
以下示範繼承兩個父類別的寫法
class SubClass(SuperClass1, SuperClass2):
pass這裡須注意一點,當子類別繼承 (inheritance) 超過一個來源的時候,會以寫在最左邊的父類別優先繼承,這是說,多個父類別如果有相同名稱的屬性 (attribute) 與方法 (method) ,例如 __init__() 、 __str__() 等,就會以最左邊的父類別優先。
因此,如果 SuperClass1 有 __init__() 、 __str__() 等, SubClass 就會繼承 SuperClass1 的 __init__() 及 __str__() ,而 SuperClass2 的 __init__() 、 __str__() 不會出現在 SubClass 之中。
以下程式示範多重繼承的這項規則
class Demo:
__x = 0
def __init__(self, i):
self.__i = i
Demo.__x += 1
def __str__(self):
return str(self.__i)
def hello(self):
print("hello " + self.__str__())
@classmethod
def getX(cls):
return cls.__x
class Other:
def __init__(self, k):
self.k = k
def __str__(self):
return str(self.k)
def hello(self):
print("hello, world")
def bye(self):
print("Good-bye!", self.__str__())
class SubDemo(Demo, Other):
def __init__(self, i, j):
super().__init__(i)
self.__j = j
def __str__(self):
return super().__str__() + "+" + str(self.__j)
a = SubDemo(12, 34)
a.hello()
a.bye()
b = SubDemo(56, 78)
b.hello()
b.bye()
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cla21.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

SubDemo 繼承自 Demo 與 Other
class SubDemo(Demo, Other):
def __init__(self, i, j):
super().__init__(i)
self.__j = j
def __str__(self):
return super().__str__() + "+" + str(self.__j)Demo 與 Other 有三個相同名稱的方法, __init__() 、 __str__() 與 hello() ,這裡 SubDemo 改寫了 __init__() 及 __str__() ,注意 super() 是呼叫 (call) Demo 的版本,而非 Other ,所以 SubDemo 的 hello() 也是 Demo 的版本。
至於 Demo 無 bye() ,因此 SubDemo 繼承 Other 的 bye() ,至於 bye() 當呼呼叫的 __str__() ,這則是 SubDemo 改寫後的版本。
| 中英文術語對照 | |
|---|---|
| 類別 | class |
| 父類別 | superclass |
| 子類別 | subclass |
| 繼承 | inherit |
| 多重繼承 | mutliple inheritance |
| 繼承 | inheritance |
| 屬性 | attribute |
| 方法 | method |
參考資料
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/compound_stmts.html
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/compound_stmts.html
沒有留言:
張貼留言