Python functions and functional Programming (2): anonymous function--lambda

Source: Internet
Author: User

Original address: http://blog.csdn.net/majianfei1023/article/details/45269343

A. Lambda function:

A lambda function is also called an anonymous function, and the function does not have a specific name. Let's take a look at one of the simplest examples:

def f (x):       return x * 2        Lambda x:x * 2  


Look at how f and g are different, f is defining a function, passing in a parameter x, then x*2,g is defining a lambda, followed by an X (this is the argument), followed by a: X * 2 (this is the operation performed), so the above f = g. They are exactly the same thing that you can write: F (10), or so write: g (10).

But what is the meaning of lambda existence? In fact, simply put,python lambda creates a function object, but does not assign the function object to an identifier, and Def assigns the function object to a variable.

For example, there are several built-in functions in Python, like map,filter,reduce, and I assume you understand their usage.

A simple programming problem: print a multiple of 3 within 100.

You might write:

def func ():       = []      for in xrange :          If i% 3 = = 0:              result.append (i )      return result  

Or if you know more about Python's features, you can filter by using filter:

def func (x):       return x%3 = =    0for in xrange (100)])  

In any case, we need to define a function, or evaluate, or filter, can not be so troublesome, so simple programming problem, every time to define a function, very troublesome, Lambda should play,

Filter (lambda for in xrange (100)])  

That's the way it's done. Note that this lambda, with the above func, does exactly the same thing, except that it does not have to be shown to define it.

A simpler approach is to use a list derivation.

Print  for inch if i%3==0]

Two. Lambda and def

In the above example, the lambda function simply creates a simple function object, which is a single-line version of a function, but the statement is called to bypass the stack allocation of the function for performance reasons. What else does Python lambda have to do with Def?

1. Python lambda creates a function object, but does not assign the function object to an identifier, and Def assigns the function object to a variable.

Such as:

def foo ():return'foo ()'>>> foo<function foo at 0x011a34f0>

2, Python Lambda It's just an expression, and DEF is a statement. A lambda expression runs like a function when it is called to create a Frame object.

Three. Use of lambda functions

Personal opinion has the following:

1. For single-line functions, using lambda can eliminate the process of defining a function, making the code more streamlined.

2. In the case of functions that are not called multiple times, lambda expressions are used to improve performance

Note: if for. In.. If you can do it, it's best not to choose lambda.

Four. Based on the finished, let's look at how we use lambda in the project:

For example, in cocos2d-x we need to add a click event to the button and then click on it to trigger.

We have a trigger function:

def Addbtnclickhander (btn,func):       # this is a generic interface and cannot  be modified.          def hander ():           " %s_name "%btn  # gets                a func (widget) return based on BTN Hander  

Let's add a click event to a button inside the function:

def Main ():       ' Enter BTN '             Addbtnclickhander (btn,onclick)        def  OnClick (widget):      Print " OnClick: ", widget  

However, we often need to pass additional parameters to the onclick Click event, such as the name of the transfer button, and so on, this time lambda is a good choice.

def Main ():       ' Enter BTN '        ' name ' Addbtnclickhander (btn, Lambda         Widget:onclick (widget,name))        def  OnClick (widget,name):      Print " OnClick: ", Widget,name  

Python functions and functional Programming (2): anonymous function--lambda

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.