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

yipeiwu_com5年前Python基础

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

"""
策略模式
"""
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设计】。

相关文章

python将字符串转变成dict格式的实现

python将字符串转变成dict格式的实现

字符串的内容是字典,需将字符串转变成字典格式 s1 = '{"lid":2,"date":"20190211","type":"1,2","page":1}' # dict的key和...

线程安全及Python中的GIL原理分析

本文讲述了线程安全及Python中的GIL。分享给大家供大家参考,具体如下: 摘要 什么是线程安全? 为什么python会使用GIL的机制? 在多核时代的到来的背景下,...

python获取微信企业号打卡数据并生成windows计划任务

python获取微信企业号打卡数据并生成windows计划任务

由于公司的系统用的是Java版本,开通了企业号打卡之后又没有预算让供应商做数据对接,所以只能自己捣鼓这个,以下是个人设置的一些内容,仅供大家参考 安装python python的安装,这...

dpn网络的pytorch实现方式

我就废话不多说了,直接上代码吧! import torch import torch.nn as nn import torch.nn.functional as F clas...

python用reduce和map把字符串转为数字的方法

python中reduce和map简介 map(func,seq1[,seq2...]) :将函数func作用于给定序列的每个元素,并用一个列表来提供返回值;如果func为None,fu...