多態(tài):在編輯時無法確定狀態(tài),在運行時才確定。由于Python為動態(tài)語言,參數(shù)類型沒定,所以本身即是多態(tài)的
1:由繼承實現(xiàn)多態(tài)
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()
結(jié)果:
Animal is moving
Dog is running
Fish is swimming
2:通過重載實現(xiàn)多態(tài)
1 #在子類中:2 3 class child:4 def start(self):5 print('....')6 super().start()7 print('......')
3:動態(tài)語言特性(參數(shù)類型不定)與鴨子模型
例子1:類實例為參數(shù)
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為實例參數(shù) obj.move() move(Animal())move(Dog())move(Fish())
----------------類作為參數(shù)-------------
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實例調(diào)用到不同的類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()
結(jié)果:
Move...
Move on Feet.
Move on Wheels.
I'm Fly.
例子2:函數(shù)名為參數(shù)
def movea():
print('Move a.')
def moveb():
print('Move b.')
class MoveObj:
def __init__(self,moveable): #moveable為函數(shù)參數(shù)
self.moveable = moveable #綁定函數(shù)名參數(shù)
self.moveable() #調(diào)用函數(shù)
if __name__ == '__main__':
a = MoveObj(movea)
b = MoveObj(moveb)
結(jié)果:
move a
move b
新聞熱點
疑難解答