[Tutor] Passing perimeters in dictionary values?

Andre Engels andreengels at gmail.com
Wed Feb 25 00:47:02 CET 2009


On Tue, Feb 24, 2009 at 8:03 PM, nathan virgil <sdragon1984 at gmail.com> wrote:
> I'm experimenting with OOP using the Critter Caretaker script from Python
> Programming for the Absolute Beginner as my basis. I've noticed that a
> dictionary/function combo is a great way to handle menus, and so I've
> adapted the menu to read as:
>
>
> selection = raw_input("Choice: ")
> choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play}
> choice = choices[selection]
> choice()
>
> so that I can call methods from a dictionary, instead of having an
> excruciatingly long if structure. Unfortunately, the problem I'm running
> into with this is that I can't pass any perimeters through the dictionary. I
> can't figure out how, for example, I could have an option that calls
> crit.eat(2) and another that calls crit.eat(4). The only thing I can think
> of is going back to the if structure, but my instinct tells me that this is
> a Bad Idea. What can I do?

You could use a tuple, consisting of the function and its parameter:

choices = {"0": (quit,), "1": (eat,2), "2": (eat,4)}
choice = choices[selection]
choice[0](*choice[1:])

But as said by someone else, if the choices are the lowest n natural
numbers, a list feels more natural:

choices = [(quit,), (eat,2), (eat,4)]
choices = choice[int(selection)]
choice[0](*choice[1:])



-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list