Python tutorial 10-Python anonymous Functions
When you pass in a function, you do not need to explicitly define the function. It is more convenient to directly pass in an anonymous function.
In Python, anonymous functions are provided with limited support. Take the map () function as an example. When f (x) = x * x is calculated, in addition to defining an f (x) function, you can also directly input an anonymous function:
From the comparison, we can see that the anonymous function lambda x: x * x is actually:
Def f (x): return x * x
The keyword lambda indicates an anonymous function, and the x before the colon indicates a function parameter.
There is a limit on anonymous functions, that is, there can be only one expression, and no return is required. The return value is the result of this expression.
There is a benefit to using an anonymous function because the function does not have a name, so you don't have to worry about function name conflicts. In addition, an anonymous function is also a function object. You can assign an anonymous function to a variable and use the variable to call the function:
Likewise, anonymous functions can be returned as return values, for example: <Strong? Http: www.bkjia.com kf ware vc "target =" _ blank "class =" keylink "> VcD4NCjxwcmUgY2xhc3M9 "brush: java;"> Def build (x, y): return lambda: x * x + y * yprint (build (3, 4 ))
Summary:
Python has limited support for anonymous functions. Anonymous functions can be used only in some simple cases.