Back: Nodes Parsing | Chapters | Next: Conclusion
Add a method def eval(self, variables) to every AST node and
recursively call eval until you reach the terminal leaves.
For now we will disregard all runtime errors.
Value
classValue(AST):
...
defeval(self, variables):
returnself.valueVariable
classVariable(AST):
...
defeval(self, variables):
returnvariables[self.name]FuncCall
classFuncCall(AST):
...
defeval(self, variables):
args= [arg.eval(variables) forarginself.args]
returnvariables[self.name](args)BinaryOp
classBinaryOp(AST):
...
defeval(self, variables):
left=self.left.eval(variables)
right=self.right.eval(variables)
ifself.op=='+':
returnleft+rightifself.op=='-':
returnleft-rightifself.op=='*':
returnleft*rightifself.op=='/':
returnleft/rightifself.op=='%':
returnleft%rightUnaryOp
classUnaryOp(AST):
...
defeval(self, variables):
item=self.item.eval(variables)
ifself.op=='+':
return+item# redundant, but ey why notifself.op=='-':
return-itemAnd we are done!
%>py main.py
2.2704074859237844