Python策略模式怎么用
发表于:2024-09-22 作者:千家信息网编辑
千家信息网最后更新 2024年09月22日,这篇文章主要介绍"Python策略模式怎么用",在日常操作中,相信很多人在Python策略模式怎么用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Python策略模式怎
千家信息网最后更新 2024年09月22日Python策略模式怎么用
这篇文章主要介绍"Python策略模式怎么用",在日常操作中,相信很多人在Python策略模式怎么用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Python策略模式怎么用"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
首先是发生器基类:
class Generator: # 初始化函数 # period:周期 def __init__(self, period): self.period= period # 计算输入值折算到最后一个周期时的占比 def rate(self, t): return(t - int(t / self.period) * self.period)/ self.period # 计算输出 def output(self, t): pass
发生器基类Gererator定义了策略接口output,其功能是根据输入的时间值计算对应的输出数据。由于信号发生器的周期性,因此在实际的处理中只要将时间值折算到一个周期之内再计算结果即可,这个折算功能就是rate方法。接下来就是具象策略类正弦发生器SinGerneator和方波发生器SquareGenerator,具体实现如下:
class SinGenerator(Generator): def __init__(self,period): Generator.__init__(self, period) # 计算输出 def output(self, t): returnsin(2 * 3.1415926* self.rate(t)) class SquareGenerator(Generator): def __init__(self,period): Generator.__init__(self, period) # 计算输出 def output(self, t): if self.rate(t) < 0.5: return-1 else:
两个具象类分别实现了output方法以输出正弦数据和方波数据。为了体验发生器策略的功能,我们设计了如下的小程序。
def test_strategy(generator):
result = ''
# 正好输出一个周期
for t in range(0, 16):
# 调用策略接口
value= generator.output(t)
# 格式化输出
result= result + '{:+.2f},'.format(round(value, 2))
print(result)
if __name__ == '__main__':
# 使用正弦策略,周期20
test_strategy(SinGenerator(16))
# 使用方波策略,周期20
test_strategy(SquareGenerator(16))
代码使用完全相同的逻辑,使用了两个信号发生器。以下是其程序执行结果:
+0.00,+0.38,+0.71,+0.92,+1.00,+0.92,+0.71,+0.38,+0.00,-0.38,-0.71,-0.92,-1.00,-0.92,-0.71,-0.38,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,-1.00,+1.00,+1.00,+1.00,+1.00,+1.00,+1.00,+1.00,+1.00,
到此,关于"Python策略模式怎么用"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!
策略
发生器
周期
输出
模式
学习
功能
数据
方法
正弦
接下来
两个
信号
信号发生器
具象
就是
接口
时间
更多
程序
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
法治江西网络安全法竞赛答案
实时数据库表结构
北邮数据库与云存储
遂宁学软件开发在哪里
厦门亿联网络技术招聘
北京手机软件开发品牌企业
网络安全中的dpi系统
黑龙江省网络安全刑事检察
嵌入式前段服务器
西安零点网络技术有限公司
乡镇网络安全宣传存在问题
乌海软件开发优缺点
画图数据库表用什么图形表示
dell的服务器
广东游戏软件开发公司排名
网络技术上机破解 百度云
软件开发增值税进项
管理软件开发软件
昌平区数据网络技术质量保证
如何知道金蝶服务器的ip地址
远程服务器管理软件有哪些
ff14 服务器ip
软件开发 本院认为
泸州教育期刊上数据库吗
数据库 封锁协议
阿里云 云数据库服务器
数据库据
万方数据库请求原文传递是否收费
新乡云鼎网络技术有限
美国服务器可以做 x站吗