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

以上就是python学习手册中的python多态示例代码的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python