Python practical notes (12) functional programming - higher-order functions

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 fnow points to the absfunction itself. Calling a abs()function directly is f()exactly the same as calling a variable.

Note: Since the absfunction is actually defined in the import builtinsmodule, it is necessary to make the point of the modified absvariable 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, yand freceive, respectively -5, 6and 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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325740609&siteId=291194637