在處理多態對象時,只需要關注它的接口即可,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'))
新聞熱點
疑難解答