1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/tests/visitor_explicit.py Sun Jul 03 20:11:13 2011 +0200
1.3 @@ -0,0 +1,44 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +class Branch:
1.7 + def __init__(self, nodes):
1.8 + self.nodes = nodes
1.9 +
1.10 + def visit(self, visitor):
1.11 + return visitor.visitBranch(self)
1.12 +
1.13 +class Leaf:
1.14 + def __init__(self, value):
1.15 + self.value = value
1.16 +
1.17 + def visit(self, visitor):
1.18 + return visitor.visitLeaf(self)
1.19 +
1.20 +class Visitor:
1.21 + def visit(self, node):
1.22 + return node.visit(self)
1.23 +
1.24 + # Visitor-specific functionality.
1.25 +
1.26 + def visitBranch(self, node):
1.27 + sum = 0
1.28 + for node in node.nodes:
1.29 + sum += self.visit(node)
1.30 + return sum
1.31 +
1.32 + def visitLeaf(self, node):
1.33 + return node.value
1.34 +
1.35 +tree = \
1.36 + Branch((
1.37 + Branch((
1.38 + Leaf(10),
1.39 + Leaf(5)
1.40 + )),
1.41 + Leaf(2)
1.42 + ))
1.43 +
1.44 +visitor = Visitor()
1.45 +result_17 = visitor.visit(tree)
1.46 +
1.47 +# vim: tabstop=4 expandtab shiftwidth=4