Using a switch-like if/else construct versus a dictionary?
Ben Finney
bignose+hates-spam at benfinney.id.au
Tue Jun 19 20:40:00 EDT 2007
asincero <asincero at gmail.com> writes:
> def foo():
> def doCase1():
> pass
> def doCase2():
> pass
> def doCase3():
> pass
> def doCase4():
> pass
> def doCase5():
> pass
>
> handle_case = {}
> handle_case[1] = doCase1()
> handle_case[2] = doCase2()
> handle_case[3] = doCase3()
> handle_case[4] = doCase4()
> handle_case[5] = doCase5()
> handle_case[c]()
(The above code is wrong. You want the dictionary to map to functions,
not to the result of calling those functions; the call to the function
comes later.)
Why not construct the dictionary in one step? ::
handle_case = {
1: do_case_1,
2: do_case_2,
3: do_case_3,
4: do_case_4,
5: do_case_5,
}
handle_case[c]()
You could even perform the lookup and function call in the same
statement as creating the dictionary, but I prefer the above form for
its readability.
> 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.
I'm not sure what you mean. What would you apply polymorphism to, and
what would be the desired result?
--
\ "I used to work in a fire hydrant factory. You couldn't park |
`\ anywhere near the place." -- Steven Wright |
_o__) |
Ben Finney
More information about the Python-list
mailing list