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

yipeiwu_com6年前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 字典操作提取key,value的方法

python 字典操作提取key,value的方法

python 字典操作提取key,value dictionaryName[key] = value 1.为字典增加一项 2.访问字典中的值 3、删除字典中的一项...

使用rst2pdf实现将sphinx生成PDF

使用rst2pdf实现将sphinx生成PDF

当初项目文档是用sphinx写的,一套rst下来make html得到一整个漂亮的在线文档。现在想要将文档导出为离线的handbook pdf,于是找到了rst2pdf这个项目,作为sp...

linux系统使用python获取cpu信息脚本分享

linux系统使用python获取cpu信息脚本分享

linux系统使用python获取cpu信息脚本分享 复制代码 代码如下:#!/usr/bin/env Pythonfrom __future__ import print_functi...

Mac中升级Python2.7到Python3.5步骤详解

下载Python3.5 for Mac 一步步安装 安装的默认路径是: /Library/Frameworks/Python.framework/Versions/3.5/ 强烈建议不要...

Django中实现一个高性能计数器(Counter)实例

计数器(Counter)是一个非常常用的功能组件,这篇blog以未读消息数为例,介绍了在 Django中实现一个高性能计数器的基本要点。 故事的开始:.count() 假设你有一个Not...