An expression like 1 + 2 can be stored as a small tree of node objects: an Add node whose children are two Num nodes. The Visitor pattern lets you add new operations over that tree (evaluate it, print it, count it) WITHOUT editing the node classes each time.
The trick is double dispatch. Each node has an accept(visitor) method that calls the one visit method matching its own type. The node picks the method by its type; the visitor supplies the behavior.
Implement accept on both node classes:
A node never knows what the visitor does. It only routes the call.
class Num:
def __init__(self, value):
self.value = value
def accept(self, visitor):
"""Dispatch to the visitor method for a Num node (double dispatch)."""
# TODO: return visitor.visit_num(self)
pass
class Add:
def __init__(self, left, right):
self.left = left
self.right = right
def accept(self, visitor):
"""Dispatch to the visitor method for an Add node (double dispatch)."""
# TODO: return visitor.visit_add(self)
passThe editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
An expression like 1 + 2 can be stored as a small tree of node objects: an Add node whose children are two Num nodes. The Visitor pattern lets you add new operations over that tree (evaluate it, print it, count it) WITHOUT editing the node classes each time.
The trick is double dispatch. Each node has an accept(visitor) method that calls the one visit method matching its own type. The node picks the method by its type; the visitor supplies the behavior.
Implement accept on both node classes:
A node never knows what the visitor does. It only routes the call.
Press Run Tests or ββ© to check your solution.