Nodes That Accept a Visitor

Step 1: Nodes That Accept a Visitor

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:

  • Num.accept(visitor) returns visitor.visit_num(self)
  • Add.accept(visitor) returns visitor.visit_add(self)

A node never knows what the visitor does. It only routes the call.

Hints
Starter code
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)
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.