多态是面向對象語言的一個基本特性,多态意味着變量并不知道引用的對象是什麼,根據引用對象的不同表現不同的行為方式。在處理多态對象時,隻需要關注它的接口即可,python中并不需要顯示的編寫(像Java一樣)接口,在使用對象的使用先假定有該接口,如果實際并不包含,在運作中報錯。
class handGun():
def __init__(self):
pass
def fire(self):
print 'handGun fire'
class carbine():
print 'carbine fire'
import handGun
import carbine
class gunFactory():
def __init__(self,gun_type):
self.gun_type = gun_type
def produce(self):
if handGun == self.gun_type:
return handGun.handGun()
else:
return carbine.carbine()
用戶端
fa = gunFactory(handGun)
gun = fa.produce()
/*隻要是槍,就認為它具有開火的功能,如果沒有開火的功能,程式運作中就報錯*/
gun.fire()
可以看到跟一般的靜态語言相比,python并沒有在語言級别來保證接口的正确性,隻能依靠文檔、代碼來保證(可以在代碼中檢查接口是否存在,hasattr(gun,'fire'))