1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Python设计模式编程中解释器模式的简单程序示例分享

Python设计模式编程中解释器模式的简单程序示例分享

时间:2019-11-07 08:04:36

相关推荐

Python设计模式编程中解释器模式的简单程序示例分享

后端开发|Python教程

Python,解释器模式,设计模式

后端开发-Python教程

模式特点:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。

asp影视源码,ubuntu官网源,tomcat中修改项目名,头条爬虫 开源,php基本表单代码,seo公司找佰蜂seolzw

我们来看一下下面这样的程序结构:

秒赞网源码破解8.0,开机ubuntu进bios,云厂商爬虫支持,php getmxrr,豆哥seolzw

class Context: def __init__(self): self.input="" self.output=""class AbstractExpression: def Interpret(self,context): passclass Expression(AbstractExpression): def Interpret(self,context): print "terminal interpret"class NonterminalExpression(AbstractExpression): def Interpret(self,context): print "Nonterminal interpret"if __name__ == "__main__": context= "" c = [] c = c + [Expression()] c = c + [NonterminalExpression()] c = c + [Expression()] c = c + [Expression()] for a in c: a.Interpret(context)

商家入驻 附近商家源码,vscode 函数追中,ubuntu删除桌面,tomcat 8.0漏洞,sqlite数据库冲突,爬虫比较高深的难题是,dedeampz-php,seo服务有哪些,医院网站栏目设置说明,转发网页源码,网页布局模板下载lzw

那么它所体现出的类图是这样的:

再来看一个例子:

#encoding=utf-8 # #by panda #解释器模式 def printInfo(info): print unicode(info, utf-8).encode(gbk), #上下文类:演奏内容 class PlayContext(): text = None PlayText = None #抽象表达式类 class Expression(): def Interpret(self, context):if len(context.PlayText) == 0: returnelse: playKey = context.PlayText[0:1] context.PlayText = context.PlayText[2:] tmp = context.PlayText.index( ) #找出第一个空格出现的位置 playValue = context.PlayText[0:tmp] context.PlayText = context.PlayText[tmp+1:] self.Excute(playKey,playValue)def Excute(self,playKey,playValue):pass #音高 class Pitch(Expression): pitch = None def Excute(self, key, value):value = int(value)if value == 1: self.pitch = 低音elif value == 2: self.pitch = 中音elif value == 3: self.pitch = 高音printInfo(self.pitch)#音符 class Note(Expression): Notes = { C:1,D:2, E:3,F:4,G:5,A:6,B:7,} note = None def Excute(self, key, value): self.note = self.Notes[key]printInfo(\%d % self.note) def clientUI(): context = PlayContext() context.PlayText = "O 2 E 0.5 G 0.5 A 3 E 0.5 G 0.5 D 3 E 0.5 G 0.5 A 0.5 O 3 C 1 O 2 A 0.5 G 1 C 0.5 E 0.5 D 3 " expression = None; while(len(context.PlayText) > 0):str = context.PlayText[0:1];if(str == O): expression = Pitch()elif(str == C or str == D or str == E or str == F or str == G or str == A or str == B or str == P): expression = Note()expression.Interpret(context)return if __name__ == \__main__: clientUI();

类图:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。