[Tutor] Passing perimeters in dictionary values?

spir denis.spir at free.fr
Tue Feb 24 20:35:24 CET 2009


Le Tue, 24 Feb 2009 14:03:09 -0500,
nathan virgil <sdragon1984 at gmail.com> s'exprima ainsi:

> 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()

This is (to my taste) very good programming practice. The only detail is that in this precise case, as keys are ordinals starting at 0, you can use a simple list instead ;-) and
	choice = choices[int(selection)]

> 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?

There is a syntactic trick for this, commonly called *args. You can call a function and pass it a variable holding a 'pack' of arguments prefixed with '*' so that the args will be automagically unpacked into the call message. Below an example:

def sum(a,b):
	return a+b
arg_list = (1,2)
func_calls = {1:sum(*arg_list)}
print func_calls[1]
==> 3

Like if I had written sum(1,2) -- except that the arg_list can now be unknown at design time!

Conversely, when you want a function to accept an arbitrary number of args, you can write its def using the * trick:

def sum(*values):
	s = 0
	for v in values : s+= v
	return s
print sum(1), sum(1,2), sum(1,2,3)
==> 1, 3, 6

There is a similar trick for named arguments using **

denis
------
la vita e estrany


More information about the Tutor mailing list