1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/tests/visitor_getattr.py Sun Jul 03 20:11:13 2011 +0200
1.3 @@ -0,0 +1,40 @@
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 +class Leaf:
1.11 + def __init__(self, value):
1.12 + self.value = value
1.13 +
1.14 +class Visitor:
1.15 + def visit(self, node):
1.16 + method = getattr(self, node.__class__.__name__)
1.17 + return method(node)
1.18 +
1.19 + # Visitor-specific functionality.
1.20 + # Note that getattr does not support "visit" + __class__.__name__.
1.21 +
1.22 + def Branch(self, node):
1.23 + sum = 0
1.24 + for node in node.nodes:
1.25 + sum += self.visit(node)
1.26 + return sum
1.27 +
1.28 + def Leaf(self, node):
1.29 + return node.value
1.30 +
1.31 +tree = \
1.32 + Branch((
1.33 + Branch((
1.34 + Leaf(10),
1.35 + Leaf(5)
1.36 + )),
1.37 + Leaf(2)
1.38 + ))
1.39 +
1.40 +visitor = Visitor()
1.41 +result_17 = visitor.visit(tree)
1.42 +
1.43 +# vim: tabstop=4 expandtab shiftwidth=4