美文网首页
Python解释器模式

Python解释器模式

作者: 虾想家 | 来源:发表于2017-03-19 17:42 被阅读49次

    解释器模式,给予一段字符串,对其 进行翻译构成语法树并计算结果。

    class Interpreter(object):
        def __init__(self, command):
            self.stack = command.split(' ')
            self.dynamic_stack = []
    
        def calculate(self):
            before_op = ""
            for one in self.stack:
                if one in ['+', '-', '*', '/']:
                    before_op = one
                else:
                    if before_op:
                        left = self.dynamic_stack.pop()
                        right = one
                        result = eval(str(left) + before_op + right)
                        self.dynamic_stack.append(result)
                        before_op = ""
                    else:
                        self.dynamic_stack.append(one)
    
            print(self.dynamic_stack)
    
    
    def main():
        Interpreter("1 + 2 + 6").calculate()
    
    
    if __name__ == '__main__':
        main()
    

    相关文章

      网友评论

          本文标题:Python解释器模式

          本文链接:https://www.haomeiwen.com/subject/lyimnttx.html