how to dispatch objects depending on their class

Casey Duncan casey at zope.com
Tue Aug 10 11:27:39 EDT 2004


It should not be a problem to use the actual class object as keys in the
dict and the functions as values. No need to convert the class to
strings.

So why can't they be static methods of the classes exactly? That would
be simpler, however the dict will work efficiently.

-Casey

On Tue, 10 Aug 2004 16:35:48 +0200
Curzio Basso <curzio.basso at unibas.ch> wrote:

> 
> Hi all.
> 
> I have a couple of question regarding the following situation:
> 
> class A(object):
>    def __init__(self):
>      pass
> 
> class B(object):
>    def __init__(self):
>      A.__init__(self)
> 
> def func(object):
>    if isinstance(object, A):
>      do_something_with_A(object)
>    elif isinstance(object, B):
>      do_something_with_B(object)
> 
> Note that in my real problem I cannot move the logic of func to the 
> class A and B because I will have a hierarchy also for func. Then I
> need a way to dispatch the object to the right function. I thought
> about using a dictionary, like:
> 
> FUNC = {"<class '__main__.A'>": do_something_with_A,
>          "<class '__main__.B'>": do_something_with_B}
> 
> def func(object):
>    FUNC[type(object)](object)
> 
> But: (1) I am not sure of what the type(object) function return. In
> this case A and B are in the __main__ namespace (assuming this is how
> is called), but if they are in a module; (2) I am not sure if it is 
> efficient; and finally (3): probably there is a better way to do it 
> (this is always a safe assumption).
> 
> I hope my problem is clear, and excuse me if I am asking about
> something that is common knowledge, but I don't even know what to
> google for...
> 
> thanks, curzio
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 




More information about the Python-list mailing list