anonymous functions
/Anonymous function
An anonymous function is a function that does not require a binding function name (i.e. functions, which is not bound to a name). Anonymous functions are built with lambda expressions. Often used to quickly establish a (one-time) function.
Note: Lambda is an expression/keyword for Python, similar to return, not a function, but the ability to generate anonymous functions.
The use of anonymous functions can be used in the following way, directly,
1 # Use directly 2 Lambda x:x+13defreturn x4print(' F type is: ' ' foo type is: ', type (foo))
The functions generated by lambda can be used directly, which may violate the concept of anonymous functions, and when a lambda function is defined by a lambda expression, it needs to be called because the function is anonymous and therefore needs to be assigned to a variable , called by the variable name. The anonymous function is now actually named , which makes it inconsistent with the concept of anonymity.
is: <class' function'is: <class' function '>
But direct use is not the best way to use anonymous functions, and the best use scenario for lambda-generated anonymous functions should be when a function requires a simple temporary function as an input parameter , using lambda Generating an anonymous function eliminates the process of defining a naming for this intermediate function . For example, when using map to square all the values of an iterative object, it is convenient to complete the square calculation with an anonymous function.
# Use as a calculate func in other function Print (List (map (Lambda x:x*x, [1, 2, 3, 4]))
Also, anonymous functions can be used in situations where a function is required to return, eliminating the need to name the function.
1 # Use as a return func in other function 2 def return Lambda x:n+x3print(foo ('n') (' x '))
Python program structure [4]--function/function---anonymous function