Lambda parameter:expression
Where lambda is the declaration of an anonymous function, parameter is the function has parameters, how many, the middle separated by commas, expression is a regular expression
def compute (A,B,FUNC): result = Func (A, b) return resultnum = Compute (11,12,LAMBDA x,y:x+y) print (num)
Method Compute has three parameters, from the encapsulated code can be seen, compute the third argument with a function, and then see the fourth line of code, the expression is x+y, so the contents of the Func parameter is x+y, and need to pass two parameters are X, Y, And look at the second line of code that passed in two parameters is a, b, then result = A + b. Because a = 11,b = 12, so result equals 23, so num equals 23, and the print result is 23.
Here's a look at the extension:
def compute (A,B,FUNC): result = Func (A, b) return resultfunc_new = input ("Enter an anonymous function:") num = Compute (11,12,func_new) PR int (num)
The above code means let's enter a function, so that you want it to be additive, it adds. Subtract if you want it to implement subtraction.
However, it can only be used in the 2.7 version of the above code, 3.6 of the words will not be, because input will be the value you entered into a cameo, that is, "Lambda x,y:x+y", you let a string to achieve this, is not funny? At this point we can use the Eval function, which is a powerful function. It can get rid of this string and make it a function that can be called, the following code
def compute (A,B,FUNC): result = Func (A, b) return resultfunc_new = input ("Enter an anonymous function:") func_new = eval (func_new) num = Compute (11,12,func_new) print (num)
This article is from "Love Zhou Yu" blog, please be sure to keep this source http://izhouyu.blog.51cto.com/10318932/1967315
Python's anonymous function lambda