Visitor design pattern for python objects?
Darrell
news at dorb.com
Tue Nov 23 14:19:48 EST 1999
How useful is the visitor pattern in Python ?
Doesn't this solve problems associated with strongly typed languages ?
One useful feature might be had if instead of visitor.visit(self)
you use visitor.myConcreteType(self)
That gives you a switch on type thing so you can avoid this:
if type(concreteType)==type(xxxx):
pass
elif type(......
#!/usr/bin/env python
"""
My twisted view of visitor in Python
Darrell Gallion
"""
class Visitor:
def __init__(self):
self._methodDic={}
def default(self, other):
print "What's this:", other
def addMethod(self, method):
self._methodDic[method.getKey()]=method
def __call__(self, other):
method=self._methodDic.get(\
other.__class__.__name__,self.default)
return method(other)
class MyVisit:
"""
Instead of deriving from Visitor the work is
done by instances with this interface.
"""
def __init__(self, otherClass):
self._msg='Visit: %s'%otherClass.__name__
self._key=otherClass.__name__
def __call__(self, target):
print self._msg, target
def getKey(self):
return self._key
# Some stuff to visit
class E1:pass
class E2:pass
class E3:pass
collection=[E1(), E1(), E2(), E3()]
visitor=Visitor()
visitor.addMethod(MyVisit(E1))
visitor.addMethod(MyVisit(E2))
map(visitor, collection)
########################### OUTPUT:
Visit: E1 <__main__.E1 instance at 7ff6d0>
Visit: E1 <__main__.E1 instance at 7ff730>
Visit: E2 <__main__.E2 instance at 7ff780>
What's this: <__main__.E3 instance at 7ff7b0>
--
--Darrell
More information about the Python-list
mailing list