Python program structure [4]--function/function---anonymous function

Source: Internet
Author: User

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

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.