Using a switch-like if/else construct versus a dictionary?
heltena
heltena at gmail.com
Tue Jun 19 16:11:43 EDT 2007
asincero ha escrit:
> 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()
Sorry, but I think this is not correct. Now, you put the result of the
function call into the dictionary, but you want the function address.
The correct code is:
handle_case = {}
handle_case[1] = doCase1
handle_case[2] = doCase2
handle_case[3] = doCase3
handle_case[4] = doCase4
handle_case[5] = doCase5
Or:
handle_case = { 1: doCase1, 2: doCase2, 3: doCase3, 4: doCase4, 5:
doCase 5 }
Or:
try:
{ 1: doCase1, 2: doCase2, 3: doCase3, 4: doCase4, 5: doCase 5 }
[c]()
except:
print "Catch the correct exception"
But this solutions only works fine if the params of the functions are
the same for all calls (in if/else construct you don't need it).
Bye!
--
Helio Tejedor
More information about the Python-list
mailing list