how to dispatch objects depending on their class
Peter Otten
__peter__ at web.de
Tue Aug 10 11:20:10 EDT 2004
Curzio Basso wrote:
> FUNC = {"<class '__main__.A'>": do_something_with_A,
> "<class '__main__.B'>": do_something_with_B}
>
> def func(object):
> FUNC[type(object)](object)
You'll have to modify that slightly for it to work. It will be very
efficient, too.
func_dict = {A: do_something_with_A,
B: do_something_with_B}
def func(obj):
func_dict[obj.__class__](obj)
Using classes as keys avoids the ambiguity you fear. The overhead will be
one dictionary lookup and a function call. The main drawback of this simple
approach is that it does not search the inheritance tree but insists on an
exact class match.
> 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...
Maybe
python generic dispatch
Peter
More information about the Python-list
mailing list