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安全错误
数据库的锁怎样保障安全
广东医学增刊进数据库收录
360网络安全总部
SEO天天网络安全
刀片服务器云计算主机
战地4服务器管理人员开挂
崇明区专业软件开发活动简介
路北区网络营销软件开发常见问题
提供数据库安全性控制
数据库 查询实例
ftp和数据库是一样的吗
网络安全模式正常使用后怎么样
广州群英互联网科技
红米手机网络安全
做小程序服务器要钱吗
深圳瑞庭网络技术上海有限公司
如何使用网络安全教育手册
mc手游服务器
服务器服务是开机启动
通过数据库查询时间锁定文件
派出所开展网络安全隐患排查
335.178数据库
网络技术服务发票代码
监狱网络安全管理岗位视力要求
众人 网络安全 技术
网络安全的百度百科
软件开发符合什么专业
服务器一般多大内存够用
菏泽网络安全平台
跟网络安全有关的主题
利用新媒体网络安全法宣传