Python tutorial 10-Python anonymous Functions

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.