26 April 2013

Assigning functions to variables

Functions can be assigned, like other Python objects,
to variables, as shown in the following example:

>>> def f_to_kelvin(degrees_f):
... return 273.15 + (degrees_f - 32) * 5 / 9
...
>>> def c_to_kelvin(degrees_c):
... return 273.15 + degrees_c
...
>>> abs_temperature = f_to_kelvin

>>> abs_temperature(32)
273.14999999999998

>>> abs_temperature = c_to_kelvin
>>> abs_temperature(0)
273.14999999999998

You can place them in lists, tuples, or dictionaries:

>>> t = {'FtoK': f_to_kelvin, 'CtoK': c_to_kelvin}

>>> t['FtoK'](32)
Accesses a function as
273.14999999999998

>>> t['CtoK'](0)
Accesses a function as
273.14999999999998

A variable that refers to a function can be used in exactly the
same way as the function q. This last example shows how you
can use a dictionary to call different functions by the value of
the strings used as keys. This is a common pattern in situations
where different functions need to be selected based on a string
value, and in many cases it takes the place of the switch structure
found in languages like C and Java.



biOos

No comments: