zoukankan      html  css  js  c++  java
  • 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'))

  • 相关阅读:
    3.db2性能和优化
    SpringBoot之demo
    1设计模式---工厂模式。
    1.添加maven项目后,tomcat启动失败
    2.如何卸载mysql
    2.hdfs中常用的shell命令
    1.在eclipse上添加maven
    2.hive入门篇
    1.hive数据库调优之路
    2.myeclipse的使用技巧
  • 原文地址:https://www.cnblogs.com/chencheng/p/2798554.html
Copyright © 2011-2022 走看看