how to dispatch objects depending on their class

Curzio Basso curzio.basso at unibas.ch
Tue Aug 10 10:35:48 EDT 2004


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



More information about the Python-list mailing list