最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2016年03月02日 15:05:07   作者:ponder008  
這篇文章主要介紹了Python設(shè)計模式編程中解釋器模式的簡單程序示例分享,解釋器模式強調(diào)用抽象類來表達(dá)程序中將要實現(xiàn)的功能,需要的朋友可以參考下

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

我們來看一下下面這樣的程序結(jié)構(gòu):

class Context:
  def __init__(self):
    self.input=""
    self.output=""

class AbstractExpression:
  def Interpret(self,context):
    pass

class 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)

那么它所體現(xiàn)出的類圖是這樣的:

201632150316773.png (682×450)

再來看一個例子:

#encoding=utf-8 
# 
#by panda 
#解釋器模式 
 
def printInfo(info): 
  print unicode(info, 'utf-8').encode('gbk'), 
 
#上下文類:演奏內(nèi)容 
class PlayContext(): 
  text = None 
  PlayText = None 
 
#抽象表達(dá)式類 
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(' ') #找出第一個空格出現(xiàn)的位置 
      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)

相關(guān)文章

最新評論

岳普湖县| 石狮市| 句容市| 吉林省| 靖州| 兴隆县| 额济纳旗| 五寨县| 彝良县| 霍州市| 边坝县| 监利县| 太原市| 广安市| 伊吾县| 宜丰县| 安塞县| 蒙山县| 新宾| 象山县| 桂林市| 基隆市| 莱西市| 江永县| 浏阳市| 贡觉县| 儋州市| 合作市| 东乡| 比如县| 海原县| 石屏县| 湘潭市| 灌南县| 海淀区| 久治县| 湄潭县| 桐城市| 高雄县| 望谟县| 辉南县|