2013-07-01 | Paul Boddie | file changeset files shortlog | Introduced numbered functions where rebinding occurs in namespaces. Added an original name attribute to classes and functions, revised the check for usage of functions when generating code or reports, and added rebinding statements to module "main program" syspython output. Fixed the attribute operation generated by syspython when acquiring module attributes for a "from" statement. | syspython-as-target |
paul@439 | 1 | #!/usr/bin/env python |
paul@439 | 2 | |
paul@439 | 3 | class Branch: |
paul@439 | 4 | def __init__(self, nodes): |
paul@439 | 5 | self.nodes = nodes |
paul@439 | 6 | |
paul@439 | 7 | class Leaf: |
paul@439 | 8 | def __init__(self, value): |
paul@439 | 9 | self.value = value |
paul@439 | 10 | |
paul@439 | 11 | class Visitor: |
paul@439 | 12 | def visit(self, node): |
paul@439 | 13 | method = getattr(self, node.__class__.__name__) |
paul@439 | 14 | return method(node) |
paul@439 | 15 | |
paul@439 | 16 | # Visitor-specific functionality. |
paul@439 | 17 | # Note that getattr does not support "visit" + __class__.__name__. |
paul@439 | 18 | |
paul@439 | 19 | def Branch(self, node): |
paul@439 | 20 | sum = 0 |
paul@439 | 21 | for node in node.nodes: |
paul@439 | 22 | sum += self.visit(node) |
paul@439 | 23 | return sum |
paul@439 | 24 | |
paul@439 | 25 | def Leaf(self, node): |
paul@439 | 26 | return node.value |
paul@439 | 27 | |
paul@439 | 28 | tree = \ |
paul@439 | 29 | Branch(( |
paul@439 | 30 | Branch(( |
paul@439 | 31 | Leaf(10), |
paul@439 | 32 | Leaf(5) |
paul@439 | 33 | )), |
paul@439 | 34 | Leaf(2) |
paul@439 | 35 | )) |
paul@439 | 36 | |
paul@439 | 37 | visitor = Visitor() |
paul@439 | 38 | result_17 = visitor.visit(tree) |
paul@439 | 39 | |
paul@439 | 40 | # vim: tabstop=4 expandtab shiftwidth=4 |