how to dispatch objects depending on their class

Peter Otten __peter__ at web.de
Wed Aug 11 05:53:21 EDT 2004


Curzio Basso wrote:

> Peter Otten wrote:
> 
>> func_dict = {A: do_something_with_A,
>>              B: do_something_with_B}
>> def func(obj):
>>     func_dict[obj.__class__](obj)
> 
> ok. it tested and it works. thanks.
> 
> now I have only to check if the Visitor Pattern is not more appropriate.

I'd say the choice of the dispatch mechanism - dictionary lookup vs Duncan
Booth's name-mangling - is independent of the question whether the visitor
pattern applies. Duncan's setup would then become something like

class VisitorMixin:
    def accept(self, visitor):
        visitor.dispatch[self.__class__](self)

class Visitor:
    def __init__(self):
        self.dispatch = {A: self.visit_A, B: self.visit_B}
    def visit_A(self, a):
        pass
    def visit_B(self, b):
        pass


Peter




More information about the Python-list mailing list