Created
August 9, 2010 14:46
-
-
Save hoffmann/515508 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Implementation of the Extrinsic Visitor Pattern in Python with support | |
for Inheritance. | |
see: http://peter-hoffmann.com/2010/extrinsic-visitor-pattern-python-inheritance.html | |
""" | |
class Node(object): pass | |
class A(Node): pass | |
class B(Node): pass | |
class C(A,B): pass | |
class Visitor(object): | |
def visit(self, node, *args, **kwargs): | |
meth = None | |
for cls in node.__class__.__mro__: | |
meth_name = 'visit_'+cls.__name__ | |
meth = getattr(self, meth_name, None) | |
if meth: | |
break | |
if not meth: | |
meth = self.generic_visit | |
return meth(node, *args, **kwargs) | |
def generic_visit(self, node, *args, **kwargs): | |
print 'generic_visit '+node.__class__.__name__ | |
def visit_B(self, node, *args, **kwargs): | |
print 'visit_B '+node.__class__.__name__ | |
a = A() | |
b = B() | |
c = C() | |
visitor = Visitor() | |
visitor.visit(a) | |
visitor.visit(b) | |
visitor.visit(c) | |
""" | |
generic_visit A | |
visit_B B | |
visit_B C | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See: http://peter-hoffmann.com/2010/extrinsic-visitor-pattern-python-inheritance.html