Рубрики
Без рубрики

Позвольте построить простой переводчик с нуля в Python, PT.05: определяющие переменные

В этом посте мы определяем переменные и используя их: переводчик класса: # Модифицированная конструкция … Помечено переводчиком, из подсчетов, Python.

В этом посте мы определяем переменные и используем их:

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

Ссылки: Парреон Twitter

Часть 6: Во время петли

Оригинал: “https://dev.to/smadev/lets-build-a-simple-interpreter-from-scratch-in-python-pt-05-defining-variables-4hek”