[portland] Dictionary As Switch Statement
kirby urner
kirby.urner at gmail.com
Fri Jan 18 02:41:31 CET 2008
> I use 'self' because I thought that the function calls needed the trailing
> parentheses to identify them as functions. When I did this, python told me
> it was expecting 1 argument for each function and I supplied 0 arguments. So
> I added 'self' and the incorrect argument number error went away.
>
> Thank you,
>
> Rich
Actually, they don't require the parentheses except to trigger them
as "callables" (a Pythonic jargon word, "iterables" being another
favorite -- dictionaries and lists are both iterables, as are generator
expressions).
So for example, you can go:
def f(x): return x * x # arbitrary function, takes x
def g(x): return x + 2 # another function
then:
myfuncs = {'square it' : f, 'add 2' : g} # a dictionary, no parentheses
Then if the user chooses "square it" for some
reason you can go:
x = 10
myfuncs["square it"](x)
where x is getting its value from somewhere in scope.
Note that myfuncs["square it"] is merely returning the
function object f, whereas the parentheses and argument
are here being supplied at runtime.
Kirby
>
> --
>
> Richard B. Shepard, Ph.D. | Integrity Credibility
> Applied Ecosystem Services, Inc. | Innovation
> <http://www.appl-ecosys.com> Voice: 503-667-4517 Fax: 503-667-8863
> _______________________________________________
> Portland mailing list
> Portland at python.org
> http://mail.python.org/mailman/listinfo/portland
>
More information about the Portland
mailing list