服务器之家

服务器之家 > 正文

轻松掌握python设计模式之策略模式

时间:2020-09-12 14:43     来源/作者:天风隼

本文实例为大家分享了python策略模式代码,供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
策略模式
"""
import types
 
class StrategyExample:
 def __init__(self, func=None):
  self.name = '策略例子0'
  if func is not None:
   """给实例绑定方法用的,不会影响到其他实例"""
   self.execute = types.MethodType(func, self)
 
 def execute(self):
  print(self.name)
 
def execute_replacement1(self):
 print(self.name + ' 从执行1')
 
 
def execute_replacement2(self):
 print(self.name + ' 从执行2')
 
 
if __name__ == '__main__':
 strat0 = StrategyExample()
 
 strat1 = StrategyExample(execute_replacement1)
 strat1.name = '策略例子1'
 
 strat2 = StrategyExample(execute_replacement2)
 strat2.name = '策略例子2'
 
 strat0.execute()
 strat1.execute()
 strat2.execute()

运行结果如图:

轻松掌握python设计模式之策略模式

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址 2020-08-12
最新idea2020注册码永久激活(激活到2100年)
最新idea2020注册码永久激活(激活到2100年) 2020-07-29
返回顶部