One of the features of functional programming is that it allows to pass a function itself as a parameter to another function, and also allows to return a function!
Python provides partial support for functional programming. Since Python allows variables, Python is not a purely functional programming language.
Variables can point to functions
>>> f = abs
>>> f(-10)
10
success! The description variable f
now points to the abs
function itself. Calling a abs()
function directly is f()
exactly the same as calling a variable.
Note: Since the abs
function is actually defined in the import builtins
module, it is necessary to make the point of the modified abs
variable take effect in other modules import builtins; builtins.abs = 10
.
incoming function
Since variables can point to functions, and function parameters can receive variables, then a function can receive another function as a parameter. This kind of function is called a higher-order function.
A simplest higher-order function:
def add(x, y, f):
return f(x) + f(y)
When we call add(-5, 6, abs)
, the parameters x
, y
and f
receive, respectively -5
, 6
and abs
, according to the function definition, we can deduce the calculation process as:
x = -5
y = 6
f = abs
f(x) + f(y) ==> abs(-5) + abs(6) ==> 11 return 11
(The function parameter can be a function, which is called a higher-order function)