2013-06-29 | Paul Boddie | file changeset files shortlog | Separated handling of getattr attribute usage from normal program unit usage, tracking only newly introduced program constants when evaluating the effects of getattr usage, and thus limiting the amount of work done identifying new program units to investigate on each occasion. | 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 |