Using a switch-like if/else construct versus a dictionary?

asincero asincero at gmail.com
Wed Jun 20 14:21:30 CEST 2007


Ahh .. yes of course, you are right.  I mis-typed.  I like how you
defined the dictionary all in one statement, though.  I didn't think
of doing it that way.

-- Arcadio


On Jun 19, 4:11 pm, heltena <helt... at gmail.com> wrote:
> 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