轻松掌握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中用PIL库批量给图片加上序号的教程

Python中用PIL库批量给图片加上序号的教程

女友让我给她论文的图片上加上字母序号,本来觉得是个很简单的事情,但那个白底黑字的圆圈序号却难住了我, 试了几个常用的软件,都不行。 后来用 PS + 动作,倒是能搞出来,不过也不容易,正...

tensorflow 打印内存中的变量方法

法一: 循环打印 模板 for (x, y) in zip(tf.global_variables(), sess.run(tf.global_variables())): pri...

Python基于递归算法实现的走迷宫问题

本文实例讲述了Python基于递归算法实现的走迷宫问题。分享给大家供大家参考,具体如下: 什么是递归? 简单地理解就是函数调用自身的过程就称之为递归。 什么时候用到递归? 如果一...

Python编程实现从字典中提取子集的方法分析

本文实例讲述了Python编程实现从字典中提取子集的方法。分享给大家供大家参考,具体如下: 首先我们会想到使用字典推导式(dictionary comprehension)来解决这个问题...

linux环境下安装pyramid和新建项目的步骤

1. 安装python虚拟环境复制代码 代码如下:virtualenv --no-site-packages env 2. 安装pyramid 复制代码 代码如下:$ env/bin/...