#interpreter pattern concept
# 문법과 구문을 번역하는 인터프리터 클래스를 기반으로 간단한 언어를 정의하는 패턴
# " 5 + 4 - 3 + 7 - 2 "

class AbstractExpression():
@staticmethod # 클래스에서 바로 호출할 수 있는 메서드 지정
# (인스턴스를 통하지 않음)
def interpret(): # 매개 변수에 self를 지정하지 않음
pass

#Terminal Expression
class Number(AbstractExpression):
def __init__(self,value):
self.value = int(value)

def interpret(self):
return self.value

def interpret(self):
return self.value

def __repr__(self):
return str(self.value)

# Non-Terminal Expression
class Add(AbstractExpression):
def __init__(self,left,right):
self.left = left
self.right = right

def interpret(self):
return self.lef.interpret()+ self.right.interpret()

def __repr__(self):
return f"({self.left} Add {self.right})"
self.left = left
self.right = right

def interpret(self):
return self.left.interpret() - self.right.interpret()

def __repr__(self):
return f"({self.left} Subtract {self.right})"

#client
SENTENCE = " 5 + 4 - 3 + 7 - 2"
print(SENTENCE)
TOKENS = SENTENCE.split(" ")
print(TOKENS)

# Manually Creating an Abstract Syntax Tree from the tokens
AST: list[AbstractExpression] = [] #python 3.9
AST.append( Add( Number(TOKENS[0]), Number(TOKENS[2]))) # 5+4
AST.append( Subtract( AST[0], Number(TOKENS[4]))) # ^ - 3
AST.append( Add( AST[1], Number(TOKENS[6]))) # ^ + 7
AST.append( Subtract( AST[2], Number(TOKENS[8]))) # ^ - 2

# use the final AST row as the root node
AST_ROOT = AST.pop()

# INterpret recursively through the full AST starting from the root
print(AST_ROOT.interpret())

# Print out a representation of the AST_Root
print(AST_ROOT)



이 코드를 실행하면


C:\pythonSingletonProject\venv\Scripts\python.exe C:\pythonSingletonProject\interpreter_pattern_ex1.py Traceback (most recent call last): File "C:\pythonSingletonProject\interpreter_pattern_ex1.py", line 53, in <module> AST.append( Add( Number(TOKENS[0]), Number(TOKENS[2]))) # 5+4 ^^^^^^^^^^^^^^^^^ File "C:\pythonSingletonProject\interpreter_pattern_ex1.py", line 14, in __init__ self.value = int(value) ^^^^^^^^^^ ValueError: invalid literal for int() with base 10: '' 5 + 4 - 3 + 7 - 2 ['', '5', '+', '4', '-', '3', '+', '7', '-', '2']


이런 오류가 자꾸 나옴,... 코드의 원형을 번형시키지 않고 문법적인 오류만 고쳐야되는데