how to dispatch objects depending on their class
Peter Abel
PeterAbel at gmx.net
Wed Aug 11 02:35:32 EDT 2004
Curzio Basso <curzio.basso at unibas.ch> wrote in message news:<4118dd4a$1 at maser.urz.unibas.ch>...
> 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
At my opinion you try to do something outside a class which should
be a basic task of OOP. Why not let the instances do their class-specific
things:
class A(object):
def __init__(self):
pass
def do_something(self):
""" Do A-specific things """
pass
class B(object):
def __init__(self):
A.__init__(self)
def do_something(self):
""" Do B-specific things """
pass
a=A()
b=B()
a.do_something()
b.do_something()
Regards
Peter
More information about the Python-list
mailing list