美文网首页
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()

相关文章

  • 02-Python解释器

    目标 解释器的作用 下载Python解释器 安装Python解释器 一. 解释器的作用 Python解释器作用:运...

  • Python解释器模式

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

  • Python基础

    简介 Python是开源的Python由很多解释器:CPython(官方),IPython(增强交互模式),PyP...

  • 运行Python程序的三种方式

    1、python和python3解释器 1) python解释器 2) python3解释器 2、交互式运行 1)...

  • 2. 使用 Python 解释器

    2. 使用 Python 解释器 2.1. 调用 Python 解释器 Python 解释器通常被安装在目标机器的...

  • 第5章 -行为型模式-解释器模式(终)

    一、解释器模式的简介 二、解释器模式的优缺点 三、解释器模式的实例

  • Python基础

    Python基础 Python是一门多范式编程语言。 Python的执行 解释器有C语言解释器,JAVA解释器,等...

  • 17.解释器模式(行为型)

    解释器模式(行为型) 解释器模式很难学,使用率很低! 一、相关概念 1). 解释器模式概述 解释器模式是一种使用频...

  • [python_doc]python_3.7_chapter.2

    第二章 使用python解释器 2.1调用python解释器 python解释器一般被存放在 /usr/local...

  • 解释器模式

    一、解释器模式介绍 二、解释器模式代码实例

网友评论

      本文标题:Python解释器模式

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