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

原文地址:https://www.cnblogs.com/pengsixiong/p/4837363.html