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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值