Pythonからの単純なインタプリタを構築します.05 :変数定義
4587 ワード
この記事では変数の定義と使用方法を示します:
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
リンク242479152Reference
この問題について(Pythonからの単純なインタプリタを構築します.05 :変数定義), 我々は、より多くの情報をここで見つけました https://dev.to/smadev/lets-build-a-simple-interpreter-from-scratch-in-python-pt-05-defining-variables-4hekテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol