Skip to content

Instantly share code, notes, and snippets.

@hoffmann
Created August 9, 2010 14:46

Revisions

  1. hoffmann revised this gist Aug 9, 2010. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion extrinsic_visitor_inheritance.py
    Original file line number Diff line number Diff line change
    @@ -2,7 +2,7 @@
    Implementation of the Extrinsic Visitor Pattern in Python with support
    for Inheritance.
    see: http://peak.telecommunity.com/DevCenter/VisitorRevisited
    see: http://peter-hoffmann.com/2010/extrinsic-visitor-pattern-python-inheritance.html
    """

    class Node(object): pass
  2. @invalid-email-address Anonymous revised this gist Aug 9, 2010. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions extrinsic_visitor_inheritance.py
    Original file line number Diff line number Diff line change
    @@ -37,3 +37,10 @@ def visit_B(self, node, *args, **kwargs):
    visitor.visit(a)
    visitor.visit(b)
    visitor.visit(c)


    """
    generic_visit A
    visit_B B
    visit_B C
    """
  3. @invalid-email-address Anonymous created this gist Aug 9, 2010.
    39 changes: 39 additions & 0 deletions extrinsic_visitor_inheritance.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    """
    Implementation of the Extrinsic Visitor Pattern in Python with support
    for Inheritance.
    see: http://peak.telecommunity.com/DevCenter/VisitorRevisited
    """

    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)