我正在尝试在 python 中实现一个简单的表达式评估器,但我被困在解析器方法中。下面是我的代码片段。
class Number:
def __init__(self,value):
self.value=value
def execute(self):
return self.value
class Plus:
def __init__(self,left,right):
self.left=left
self.right=right
def execute(self):
return self.left+self.right
class Minus:
def __init__(self,left,right):
self.left=left
self.right=right
def execute(self):
return self.left-self.right
class Multiply:
def __init__(self,left,right):
self.left=left
self.right=right
def execute(self):
return self.left*self.right
import re
def parser(input):
stack=[]
token_pat = re.compile("\s*(?:(\d+)|(.))")
for number, operator in token_pat.findall(input):
if number:
stack.append(Number(int(number)))
else:
first,second=stack.pop(),stack.pop()
if operator=="+":
stack.append(Plus(first,second))
elif operator=="-":
stack.append(Minus(first,second))
elif operator=="*":
stack.append(Multiply(first,second))
else:
raise SyntaxError("unknown operator")
print stack[0].execute()
if __name__=="__main__":
parser('1 2 +')
当我运行上述代码时,出现以下错误。任何人都可以查看我的代码。
Traceback (most recent call last):
File "Interpreter.py", line 52, in <module>
parser('1 2 +')
File "Interpreter.py", line 48, in parser
print stack[0].execute()
File "Interpreter.py", line 12, in execute
return self.left+self.right
TypeError: unsupported operand type(s) for +: 'instance' and 'in