zoukankan      html  css  js  c++  java
  • Python多态

    多态:在编辑时无法确定状态,在运行时才确定。由于Python为动态语言,参数类型没定,所以本身即是多态的

    1:由继承实现多态

     1 class Animal:
     2     def move(self):
     3         print('Animal is moving')
     4 
     5 class Dog:
     6     def move(self):
     7         print('Dog is running')
     8 
     9 class Fish:
    10     def move(self):
    11         print('Fish is swimming')
    12 
    13 Animal().move()
    14 Dog().move()
    15 Fish().move()

    结果:

    Animal is moving
    Dog is running
    Fish is swimming

    2:通过重载实现多态

    1 #在子类中:
    2 
    3 class child:
    4     def start(self):
    5         print('....')
    6         super().start()
    7         print('......')

    3:动态语言特性(参数类型不定)与鸭子模型

    例子1:类实例为参数

    class Animal:
        def move(self):
            print('Animal is moving')
    
    class Dog:
        def move(self):
            print('Dog is running')
    
    class Fish:
        def move(self):
            print('Fish is swimming')
    
    def move(obj):        #obj为实例参数
        obj.move()
                
    
    move(Animal())
    move(Dog())
    move(Fish())

    ----------------类作为参数-------------

    class Moveable:
        def move(self):
            print('Move...')
    
    class MoveOnFeet(Moveable):
        def move(self):
            print("Move on Feet.")
    
    class MoveOnWheel(Moveable):
        def move(self):
            print("Move on Wheels.")
            
    #-------------------------------------------------------------------
            
    class MoveObj:
        def set_move(self,moveable):                                #moveable为类
            self.moveable = moveable()
    
        def move(self):
            self.moveable.move()                               #通过moveable实例调用到不同的类
    
    class Test:
        def move(slef):
            print("I'm Fly.")
    
    if __name__ == '__main__':
        m = MoveObj()
        
        m.set_move(Moveable)
        m.move()
        
        m.set_move(MoveOnFeet)
        m.move()
        
        m.set_move(MoveOnWheel)
        m.move()
        
        m.set_move(Test)
        m.move()

    结果:

    Move...
    Move on Feet.
    Move on Wheels.
    I'm Fly.

    例子2:函数名为参数

    def movea():
    print('Move a.')

    def moveb():
    print('Move b.')

    class MoveObj:
    def __init__(self,moveable): #moveable为函数参数
    self.moveable = moveable #绑定函数名参数
    self.moveable() #调用函数


    if __name__ == '__main__':
    a = MoveObj(movea)
    b = MoveObj(moveb)

    结果:

    move a

    move b

  • 相关阅读:
    奖券数目
    用jQuery和ajax实现搜索框文字自动补全功能
    简单的文件上传功能实现(java)
    示例演示公告通知标题无缝向上滚动,文字段落无缝向上滚动,简单的wangeditor富文本编辑器,简单的音乐播放demo
    SSM框架中注解含义及应用场景小结
    数据库优化以及SQL优化小结
    javaWEB中前后台乱码解决问题小结
    线程同步的方法
    MySQL的简单使用
    springMVC运行流程图及运行原理
  • 原文地址:https://www.cnblogs.com/pengsixiong/p/4837363.html
Copyright © 2011-2022 走看看