forked from faif/python-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisitor.py
More file actions
Latest commit
34 lines (27 loc) · 848 Bytes
/
Copy pathvisitor.py
File metadata and controls
34 lines (27 loc) · 848 Bytes
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
'''http://peter-hoffmann.com/2010/extrinsic-visitor-pattern-python-inheritance.html'''
classNode(object): pass
classA(Node): pass
classB(Node): pass
classC(A,B): pass
classVisitor(object):
defvisit(self, node, *args, **kwargs):
meth=None
forclsinnode.__class__.__mro__:
meth_name='visit_'+cls.__name__
meth=getattr(self, meth_name, None)
ifmeth:
break
ifnotmeth:
meth=self.generic_visit
returnmeth(node, *args, **kwargs)
defgeneric_visit(self, node, *args, **kwargs):
print('generic_visit '+node.__class__.__name__)
defvisit_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)