micropython

tests/visitor_getattr.py

513:e43264ed5c5d
2012-06-03 Paul Boddie Added missing operator handler.
     1 #!/usr/bin/env python     2      3 class Branch:     4     def __init__(self, nodes):     5         self.nodes = nodes     6      7 class Leaf:     8     def __init__(self, value):     9         self.value = value    10     11 class Visitor:    12     def visit(self, node):    13         method = getattr(self, node.__class__.__name__)    14         return method(node)    15     16     # Visitor-specific functionality.    17     # Note that getattr does not support "visit" + __class__.__name__.    18     19     def Branch(self, node):    20         sum = 0    21         for node in node.nodes:    22             sum += self.visit(node)    23         return sum    24     25     def Leaf(self, node):    26         return node.value    27     28 tree = \    29     Branch((    30         Branch((    31             Leaf(10),    32             Leaf(5)    33             )),    34         Leaf(2)    35         ))    36     37 visitor = Visitor()    38 result_17 = visitor.visit(tree)    39     40 # vim: tabstop=4 expandtab shiftwidth=4