python学习手册中的python多态示例代码

2018-09-21 21:29

阅读:606

  在处理多态对象时,只需要关注它的接口即可,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))


评论


亲,登录后才可以留言!