轻松掌握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目录和文件处理总结详解

1、判断目录是否存在、判断文件是否存在、创建目录、重命名目录或文件 import os #获取当前目录路径: E:\Work\Projects\python print(os.ge...

Python创建xml文件示例

本文实例讲述了Python创建xml文件的方法。分享给大家供大家参考,具体如下: 这是一个使用ElementTree有关类库,生成xml文件的例子 # *-* coding=utf-...

Python3实现的字典、列表和json对象互转功能示例

本文实例讲述了Python3实现的字典、列表和json对象互转功能。分享给大家供大家参考,具体如下: python3可以使用json模块操作json json.dumps(): 对jso...

基于python全局设置id 自动化测试元素定位过程解析

背景: 在自动化化测试过程中,不方便准确获取页面的元素,或者在重构过程中方法修改造成元素层级改变,因此通过设置id准备定位。 一、python准备工作: 功能:用自动化的方式进行批量处理...

Django后台管理系统的图文使用教学

Django后台管理系统的图文使用教学

django后台管理系统的使用检查配置文件 检查根urls.py文件 启动项目,浏览器输入ip端口/admin 如: 127.0.0.1/8000/admin 回车 注册后台管理...