Now add the first real operation as a visitor object. EvalVisitor turns a tree into a number.
Because accept already routes each node to the right method, the visitor just fills in behavior:
Notice the recursion: to evaluate an Add, you ask each child to accept the same visitor. The node classes stay untouched. The whole operation lives in one visitor.
class Num:
def __init__(self, value):
self.value = value
def accept(self, visitor):
return visitor.visit_num(self)
class Add:
def __init__(self, left, right):
self.left = left
self.right = right
def accept(self, visitor):
return visitor.visit_add(self)
class EvalVisitor:
def visit_num(self, node):
"""Return the numeric value of a Num node."""
# TODO: return node.value
pass
def visit_add(self, node):
"""Return the sum of evaluating both children."""
# TODO: return node.left.accept(self) + node.right.accept(self)
passThe editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Now add the first real operation as a visitor object. EvalVisitor turns a tree into a number.
Because accept already routes each node to the right method, the visitor just fills in behavior:
Notice the recursion: to evaluate an Add, you ask each child to accept the same visitor. The node classes stay untouched. The whole operation lives in one visitor.
Press Run Tests or ββ© to check your solution.