多態是面向對象語言的一個基本特性,多態意味着變量並不知道引用的對象是什么,根據引用對象的不同表現不同的行為方式。在處理多態對象時,只需要關注它的接口即可,python中並不需要顯示的編寫(像Java一樣)接口,在使用對象的使用先假定有該接口,如果實際並不包含,在運行中報錯。
class handGun():
def __init__(self):
pass
def fire(self):
print 'handGun fire'
class carbine():
def __init__(self):
pass
def fire(self):
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'))