python, pt.05에서 처음부터 간단한 인터프리터를 구축할 수 있습니다. 변수 정의

이 게시물에서는 변수를 정의하고 사용합니다.

class Interpreter:

    # Modified constructor: scope is list of dicts
    # First dict holds global variables, 
    # Last dict holds called function's scope variables

    def __init__(self):
        self.scope=[{}]

    # ....(previous code).... 

    # When we call Set we always create or update variable
    # in last scope: 

    def Set(self,xs):
        _, key, val = xs
        self.scope[-1][key] = self.eval(val)

    # When we call Get we first look into last scope(function scope),
    # if variable is not found then we look into first scope(globals)    
    def Get(self,xs):
        _, var = xs
        if var in self.scope[-1]:
            return self.scope[-1][var]
        elif var in self.scope[0]:
            return self.scope[0][var]
        raise Exception("error: variable not found: "+var)


code=[

    ["Set","answer",  ["Mul",6, 7],  ],
    ["Print", "Answer is: ", ["Get", "answer"] ]
]

interpreter=Interpreter()

interpreter.run(code)


산출:

Answer is: 42


링크: Patreon

좋은 웹페이지 즐겨찾기