解释器模式,给予一段字符串,对其 进行翻译构成语法树并计算结果。
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()
网友评论