Python解释器

1.实现变量相加的简易版

what_to_execute={
    "instructions":[("LOAD_VALUE",0),
                    ("STORE_NAME",0),
                    ("LOAD_VALUE",1),
                    ("STORE_NAME",1),
                    ("LOAD_NAME",0),
                    ("LOAD_NAME",1),
                    ("ADD_TWO_VALUES",None),
                    ("PRINT_ANSWER",None)],
                    #instruction代表指令,0与1代表其在number中的key
    "numbers":[12,8],
    "names":['a','b']
}
#()为元组,[]为列表,{}为字典,元组的特点是不可修改

class Interpreter:
    def __init__(self):
        self.stack=[]
        self.enviorment={}#存储变量与变量指向的值

    def LOAD_VALUE(self,number):
        self.stack.append(number)

    def PRINT_ANSWER(self):
        answer=self.stack.pop()
        print(answer)
    
    def ADD_TWO_VALUES(self):
        first_num=self.stack.pop()
        second_num=self.stack.pop()
        total=first_num+second_num
        self.stack.append(total)

    def STORE_NAME(self,name):
        val=self.stack.pop()
        self.enviorment[name]=val

    def LOAD_NAME(self,name):
        val=self.enviorment[name]
        self.stack.append(val)#即将变量的值取出放入stack中

    def parse_argument(self,instruction,argument,what_to_execute):
        #解析命令参数
        numbers=["LOAD_VALUE"]#使用常量列表
        names=["LOAD_NAME","STORE_NAME"]
        if instruction in numbers:
            argument=what_to_execute["numbers"][argument]
        elif instruction in names:
            argument=what_to_execute["names"][argument]
        return argument

    def execute(self,what_to_execute):
        instructions = what_to_execute["instructions"]
        for each_step in instructions:
            instruction, argument = each_step
            argument = self.parse_argument(instruction, argument, what_to_execute)
            bytecode_method = getattr(self, instruction)
            if argument is None:
                bytecode_method()
            else:
                bytecode_method(argument)

            '''
            if instruction=='LOAD_VALUE':
                self.LOAD_VALUE(argument)
            elif instruction=='PRINT_ANSWER':
                self.PRINT_ANSWER()
            elif instruction=='ADD_TWO_VALUES':
                self.ADD_TWO_VALUES()
            elif instruction=='STORE_NAME':
                self.STORE_NAME(argument)
            elif instruction=='LOAD_NAME':
                self.LOAD_NAME(argument)
            '''
test=Interpreter()
test.execute(what_to_execute)

你可能感兴趣的:(Python解释器)