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 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'))

原文地址:https://www.cnblogs.com/chencheng/p/2798554.html