1.让一个对象的某个方法可以随时改变,而不用更改对象的代码
2.对于动态类型的Python语言,不需要定义接口
3.基本的实现方法:用类作为参数传递
例如:
12_eg3.py
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):
self.moveable = moveable()
def move(self):
self.moveable.move()
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()
程序的运行结果为:
4.最简的实现方法:函数作为参数来传递
例如:
def movea():
print('Move a.')
def moveb():
print('Move b.')
class MoveObj:
def set_move(self,moveable):
self.moveable = moveable
def move(self):
self.moveable()
if __name__ == '__main__':
m = MoveObj()
m.set_move(movea)
m.move()
m.set_move(moveb)
m.move()
程序的运行结果为: