加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 20:18:38 所属栏目:Python 来源:网络整理
导读:本文实例为大家分享了python策略模式代码,供大家参考,具体内容如下 """策略模式"""import typesclass StrategyExample: def __init__(self,func=None): self.name = '策略例子0' if func is not None: """给实例绑定方法用的,不会影响到其他实例""" self.

本文实例为大家分享了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()

运行结果如图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读