Skip to content

Instantly share code, notes, and snippets.

@magthe
Created May 24, 2014 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magthe/ad6e23fb560a8a494fd2 to your computer and use it in GitHub Desktop.
Save magthe/ad6e23fb560a8a494fd2 to your computer and use it in GitHub Desktop.
Visitor and Walkabout : http://therning.org/magnus/?p=1159
# A visitor pattern implementation in Python
class Visitor:
def visit(self, obj):
func_name = 'visit_' + obj.__class__.__name__
visit_func = getattr(self, func_name)
visit_func(obj)
def visit_Tree(self, obj):
pass
class Tree:
def __init__(self, value, children=[]):
self.value = value
self.children = children
def accept(self, visitor):
visitor.visit(self)
for c in self.children:
c.accept(visitor)
class TreePrintVisitor(Visitor):
def visit_Tree(self, obj):
print('Tree (%s): %i' % (hex(id(obj)), obj.value))
def test_visitor():
leaves = [Tree(42), Tree(17)]
tree = Tree(1, leaves)
printer = TreePrintVisitor()
tree.accept(printer)
# A walkabout pattern implementation in Python
class Walkabout:
def visit(self, obj):
func_name = 'visit_%s' % obj.__class__.__name__
if hasattr(self, func_name):
visit_func = getattr(self, func_name)
visit_func(obj)
elif hasattr(obj, '__dict__'):
for m in obj.__dict__.keys():
self.visit(getattr(obj, m))
class Tree:
def __init__(self, value, children=[]):
self.value = value
self.children = children
class TreePrintWalkabout(Walkabout):
def visit_Tree(self, tree):
print('Tree (%s): %i' % (hex(id(tree)), tree.value))
for c in tree.children:
self.visit(c)
def test_walkabout():
leaves = [Tree(42), Tree(17)]
tree = Tree(1, leaves)
printer = TreePrintWalkabout()
printer.visit(tree)
# A modified walkabout pattern implementation in Python
class WalkaboutTwo:
def visit(self, obj):
func_name = 'visit_%s' % obj.__class__.__name__
descend = True
if hasattr(self, func_name):
visit_func = getattr(self, func_name)
descend = visit_func(obj)
if descend and hasattr(obj, '__dict__'):
for m in obj.__dict__.keys():
self.visit(getattr(obj, m))
if descend and hasattr(obj, '__iter__'):
for o in obj:
self.visit(o)
class Tree:
def __init__(self, value, children=[]):
self.value = value
self.children = children
class TreePrintWalkabout(WalkaboutTwo):
def visit_Tree(self, tree):
print('Tree (%s): %i' % (hex(id(tree)), tree.value))
return True
def test_walkabouttwo():
leaves = [Tree(42), Tree(17)]
tree = Tree(1, leaves)
printer = TreePrintWalkabout()
printer.visit(tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment