[Tutor] Apply()

Bob Gailer ramrom@earthling.net
Wed Feb 5 13:50:12 2003


--=======1ABB75D6=======
Content-Type: text/plain; x-avg-checked=avg-ok-66062ABC; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 11:03 AM 2/5/2003 -0500, Jim Beckstrom wrote:
>An explanation of the use of apply(), please.

Mechanics: apply(function, sequence-of-positional-parameters, 
mapping-of-named-parameters)

This lets you write code that calls an arbitrary function with arbitrary 
parameters. Say you create a set of functions; they all expect the same 
parameters; they do different things. It is only at execution time that the 
program chooses one of these based on some conditions. Instead of a series 
of if ... elif statements you use apply to "apply" the chosen function to 
the arguments.

# define functions
def a1(b,c):blah blah
def a2(b,c):blah blah
...
# associate functions with some key
dict = (1:a1, 2:a2, ...}
# determine which function to use
func_key = result of some calculation or user input
# apply that function
apply(dict[func_key], (values for b and c))

#is equivalent to:
if func_key == 1:a1(values for b and c)
elif func_key == 2:a2(values for b and c)


Bob Gailer
mailto:ramrom@earthling.net
303 442 2625

--=======1ABB75D6=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-66062ABC
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003

--=======1ABB75D6=======--