Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Visitor and Walkabout : http://therning.org/magnus/?p=1159

View visitor.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
# 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)
View visitor.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
# 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)
View visitor.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
# 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
Something went wrong with that request. Please try again.