I'm not familiar with lambdas yet, and I don't think this book will introduce me to them; they aren't listed in the index, anyway.
Adding a bunch of single-line functions would work, but I'm not sure how much better that is then the if structure. I think it's what I'm going to go with, anyway. At least until I can learn about lambdas, or even some other solution. On Tue, Feb 24, 2009 at 2:42 PM, Kent Johnson <ken...@tds.net> wrote: > On Tue, Feb 24, 2009 at 2:03 PM, nathan virgil <sdragon1...@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 can define a function that does what you want: > def eat2(): > crit.eat(2) > > Then put eat2 in your dictionary: > choices = { '2': eat2, ...} > > Alternately you can use lambda expressions to do the same thing > without an explicit def: > choices = { '2': lambda: crit.eat(2), ... } > > Kent >
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor