Functions are objects, like everything else in Python. One may pass functions as arguments, change their names, or delete them. For example:
def square(x): """ Return the square of x """ return x ** 2 square(4) # 16 sq = square # now sq is the same as square sq(4) # 16 del square # square doesn't exist anymore print(newton(sq, .2)) # passing as argument
Passing functions as arguments is very common when applying algorithms in scientific computing. The functions fsolve
in scipy.optimize
for computing a zero of a given function or quad
in scipy.integrate
for computing integrals are typical examples.
A function itself can have a different number of arguments with differing types. So, when passing your function f
to another function g
as argument, make sure that f
has exactly the form described in the docstring of g
.
The docstring of fsolve
gives information about its func
parameter:
func -- A Python function or method which takes at least one (possibly vector) argument.
Let's start with an example of a function with two variables.
The function can be viewed as a function in two variables. Often one considers ω not as a free variable but as a fixed parameter of a family of functions fω:
This interpretation reduces a function in two variables to a function in one variable, t
, given a fixed parameter value ω. The process of defining a new function by fixing (freezing) one or several parameters of a function is called partial application.
Partial applications are easily created using the Python module functools
, which provides a function called partial
for precisely this purpose. We illustrate this by constructing a function that returns a sine for a given frequency:
import functools def sin_omega(t, freq): return sin(2 * pi * freq * t) def make_sine(frequency): return functools.partial(sin_omega, freq = frequency)
Using the view that functions are objects, partial applications can be realized by writing a function, which itself returns a new function, with a reduced number of input arguments. For instance, the function could be defined as follows:
def make_sine(freq): "Make a sine function with frequency freq" def mysine(t): return sin_omega(t, freq) return mysine
In this example the inner function mysine
has access to the variable freq
; it is neither a local variable of this function nor is it passed to it via the argument list. Python allows such a construction (refer to Namespaces section in Chapter 11, Namespaces, Scopes, and Modules).
18.224.59.192