Higher-order functions English is called Higher-order function. What is a higher order function? We take the actual code as an example, step-by-step in-depth concepts.
variables can point to functions
Take the function abs (), which is built into Python, to call the function with the following code:
But what if only the ABS is written?
>>> ABS
<built-in function abs>
Visible, ABS (-10) is a function call, and ABS is the function itself.
To get the result of a function call, we can assign the result to a variable:
>>> x = ABS ( -10)
>>> x
10
But what if the function itself is assigned to a variable?
>>> f = ABS
>>> f
<built-in function abs>
Conclusion: The function itself can also be assigned to a variable, that is, a variable can point to a function.
If a variable points to a function, is it possible to call this function through the variable? Verify with code:
>>> f = ABS
>>> f ( -10)
10
Success! The description variable F now points to the ABS function itself.
The function name is also a variable
So what is the name of the function? The function name is actually a variable that points to a function! For the ABS () function, it is possible to think of the functions of ABS as a variable, which points to a function that can calculate absolute value!
What happens if you point the ABS to another object?
>>> ABS =
>>> ABS ( -10)
Traceback (most recent call last):
File "<stdin>", line 1, I n <module>
typeerror: ' int ' object is not callable
After pointing the ABS to 10, you can't call the function through ABS (-10)! Because the ABS this variable has not pointed to the absolute value function!
Of course, the actual code can never be so written, here is to illustrate that the function name is also a variable. To restore the ABS function, restart the Python interactive environment.
Note: Since the ABS function is actually defined in the __builtin__ module, the point to modify the ABS variable is also in effect in other modules, to be __builtin__.abs = 10.
Incoming function
Since a variable can point to a function, and a function's argument can receive a variable, a function can receive another function as a parameter, a function called a higher-order function.
One of the simplest higher-order functions:
def add (x, Y, f): Return
F (x) + f (Y)
When we call Add ( -5, 6, ABS), the parameters X,y and F respectively receive -5,6 and ABS, and according to the function definition, we can deduce that the calculation process is:
X ==>-5
y ==> 6
F ==> ABS
F (x) + f (Y) ==> abs ( -5) + ABS (6) ==> 11
Verify with code:
Writing higher-order functions allows the function's arguments to receive other functions.
Summary
By passing functions as arguments, such functions are called higher-order functions, and functional programming refers to this highly abstract programming paradigm.