轻松掌握python设计模式之策略模式
作者:天风隼 时间:2022-01-19 00:17:15
本文实例为大家分享了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如何实现小程序 无限求和平均
2023-04-13 20:07:40
python实现文本文件合并
2022-01-06 04:30:27
浅谈MySQL数据查询太多会OOM吗
2024-01-19 19:04:20

VUE预渲染及遇到的坑
2023-07-02 17:08:34

企业级使用LAMP源码安装教程
2024-01-17 19:41:29

Python面向对象编程基础实例分析
2023-03-31 16:39:58
golang编程入门之http请求天气实例
2024-05-09 09:32:00

PyTorch上实现卷积神经网络CNN的方法
2023-10-30 11:37:05
Python面向对象之类和对象属性的增删改查操作示例
2021-11-06 14:20:40
Mysql联合查询UNION和Order by同时使用报错问题的解决办法
2024-01-12 18:44:35
离线安装Pyecharts的步骤以及依赖包流程
2021-12-16 11:43:12

python中日期和时间格式化输出的方法小结
2023-07-01 11:39:31
pytorch中使用LSTM详解
2021-01-08 04:27:10

Python新建项目自动添加介绍和utf-8编码的方法
2023-02-07 07:58:06

python3 使用Opencv打开USB摄像头,配置1080P分辨率的操作
2024-01-02 12:40:07
php 一维数组的循环遍历实现代码
2023-06-12 00:49:04

Pygame Font模块使用教程
2021-06-17 15:23:44

vue自定义指令directive的使用方法
2024-05-09 10:43:39

Python列表1~n输出步长为3的分组实例
2021-10-31 04:25:27
通过sql语句将blob里的char取出来转成数字保存在其它字段
2024-01-20 10:49:05
