国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python設計模式編程中解釋器模式的簡單程序示例分享

2019-11-25 16:54:12
字體:
來源:轉載
供稿:網友

模式特點:給定一個語言,定義它的文法的一種表示,并定義一個解釋器,這個解釋器使用該表示來解釋語言中的句子。

我們來看一下下面這樣的程序結構:

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)

那么它所體現出的類圖是這樣的:

201632150316773.png (682×450)

再來看一個例子:

#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:       return     else:       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(); 


類圖:

201632150401221.gif (695×368)

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 浏阳市| 彩票| 铜川市| 萍乡市| 阿鲁科尔沁旗| 都兰县| 寻乌县| 岱山县| 永康市| 应城市| 资兴市| 西畴县| 延安市| 全南县| 洪泽县| 江津市| 从江县| 城步| 鸡西市| 翁源县| 南川市| 奉节县| 泸定县| 合川市| 余江县| 忻州市| 南康市| 融水| 宜阳县| 广汉市| 宜宾市| 兴和县| 温宿县| 龙岩市| 汝州市| 马公市| 贵定县| 民丰县| 白山市| 六枝特区| 同德县|