Using a switch-like if/else construct versus a dictionary?
Nick Craig-Wood
nick at craig-wood.com
Tue Jun 19 17:30:05 EDT 2007
asincero <asincero at gmail.com> wrote:
> Which is better: using an if/else construct to simulate a C switch or
> use a dictionary? Example:
Here is a technique I've used a lot. I think I learnt it from "Dive
into Python"
class foo(object):
def do_1(self):
print "I'm 1"
def do_2(self):
print "I'm 2"
def do_3(self):
print "I'm 3"
def do_4(self):
print "I'm 4"
def do_5(self):
print "I'm 5"
def dispatch(self, x):
getattr(self, "do_"+str(x))()
f = foo()
f.dispatch(1)
f.dispatch(3)
f.dispatch(17)
It will blow up gracelessly with an AttributeError if you pass it
something which it can't handle. That is easy to fix.
You could name dispatch, __call__ if you wanted a slightly neater
syntax.
f = foo()
f(1)
f(3)
f(17)
You can do the same thing in a function using locals()["do_"+str(x)]
but I always find that if I've got to that point I should be using a
class instead.
> Note that in this situation using OO polymorphism instead of a switch-
> like construct wouldn't be applicable, or at least I can't see how it
> could be.
If there is a "type" or "id" in your objects and you are switching on
it, then you should be using polymorphism. Make each seperate "type"
a seperate class type and implement the methods for each one. All the
switches will disappear from your code like magic!
Post more details if you want more help!
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list