Python解释器模式

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

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()
    原文作者:meet_future
    原文地址: https://blog.csdn.net/meet_future/article/details/79343287
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞