how to dispatch objects depending on their class

Duncan Booth duncan.booth at invalid.invalid
Wed Aug 11 05:08:58 EDT 2004


Curzio Basso <curzio.basso at unibas.ch> wrote in 
news:4119d33c$1 at maser.urz.unibas.ch:

> Is it correct that in the visitor pattern the dispatching would be 
> delegated to the classes, like with:
> 
<snip>

> Is this correct?
> 
Roughly yes, but with a dynamic language like Python you can easily extract 
the implementation out into a mixin class rather than repeating what is 
essentially the same code everywhere. e.g.

>>> class VisitorMixin:
	def accept(self, visitor):
		getattr(visitor, 'visit_' + self.__class__.__name__)(self)

		
>>> class A(object, VisitorMixin): pass

>>> class B(A): pass

>>> class Visitor:
	def visit_A(self, object):
		print "Visiting an A", object
	def visit_B(self, object):
		print "Visiting a B", object

		
>>> a = A()
>>> b = B()
>>> v = Visitor()
>>> a.accept(v)
Visiting an A <__main__.A object at 0x00A8BF10>
>>> b.accept(v)
Visiting a B <__main__.B object at 0x00A8B530>
>>> 

In practice the accept function could be more complicated, e.g. visiting 
child objects or handling errors more intelligently.



More information about the Python-list mailing list