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

  • 相关阅读:
    祖传屎山代码
    WebService原理及重要术语
    ML-For-Beginners
    Row Level Security行级数据安全,简称RLS。
    浅析 Dapr 里的云计算设计模式
    讲师征集| .NET Conf China 2021正式启动
    为什么 Dapr 如此令人兴奋
    Open Application Model(OAM)的 Kubernetes 标准实现 Crossplane 项目 成为 CNCF 孵化项目
    kubectl 的插件管理工具krew
    PrimeBlazor 组件以MIT 协议开源
  • 原文地址:https://www.cnblogs.com/pengsixiong/p/4837363.html
Copyright © 2011-2022 走看看