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

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

Posted in 未分类

发表评论