简体   繁体   English

包含 lambda 表达式的 function 背后的机制是什么? (Python)

[英]What is the mechanism behind a function that contains a lambda expression? (Python)

During a tutorial I stumbled upon the following example.在教程中,我偶然发现了以下示例。 I get the general purpose and mechanism of functions.我得到了函数的一般目的和机制。 They get parameters such as "a", "b" and "c" (example below).他们得到诸如“a”、“b”和“c”之类的参数(下面的例子)。 But how come that we can "link" the function to an object f that itself can contain 0 as parameters that will then be computed by our lambda expression?但是为什么我们可以将 function “链接”到 object f本身可以包含0作为参数,然后由我们的 lambda 表达式计算?

def build_quadratic_function(a,b,c):
     return lambda x: a*x**2 + b*x+c

f = build_quadratic_function(2,3,-5)

f(0)

yields:产量:

-5

In layman words, how does the function "know" that 0 must be read by the lambda expression that is contained in the function?通俗地说,function 如何“知道” 0必须由 function 中包含的 lambda 表达式读取? Can somebody explain the mechanism behind it?有人可以解释它背后的机制吗?

Thank you!谢谢!

def build_quadratic_function(a,b,c):
     return lambda x: a*x**2 + b*x + c

is (in all important aspects) equivalent to (在所有重要方面)等同于

def build_quadratic_function(a,b,c):
    def func(x):
        return a*x**2 + b*x + c      
    return func

In both cases, the inner function, be it an anonymous one or not, is holding onto the variables in the enclosing scope.在这两种情况下,内部 function,无论是否匿名,都持有封闭scope 中的变量。 You have discovered so called closures.你已经发现了所谓的闭包。

>>> import inspect
>>> f = build_quadratic_function(2, 3, -5)
>>> inspect.getclosurevars(f)
ClosureVars(nonlocals={'a': 2, 'b': 3, 'c': -5}, globals={}, builtins={}, unbound=set())

A very similar example can be found in the documentation .文档中可以找到一个非常相似的示例。

Lambdas are small anonymous functions. Lambda 是小型匿名函数。 They can be used wherever function objects are required.它们可以在需要 function 对象的任何地方使用。 They are syntactically restricted to a single expression.它们在语法上仅限于单个表达式。 Semantically, they are just syntactic sugar for a normal function definition.从语义上讲,它们只是普通 function 定义的语法糖。 Like nested function definitions, lambda functions can reference variables from the containing scope.与嵌套的 function 定义一样,lambda 函数可以引用包含 scope 的变量。

Therefore if you define a custom function that contains a lambda, and then fix its parameters, it's essentially the same as defining a lambda function and then passing the expression. Therefore if you define a custom function that contains a lambda, and then fix its parameters, it's essentially the same as defining a lambda function and then passing the expression.

For the sake of your example:为了您的示例:

def build_quadratic_function(a,b,c):
     return lambda x: a*x**2 + b*x+c

f = build_quadratic_function(2,3,-5)

Would create the same output as:将创建相同的 output 为:

f = lambda x: 2*x**2 + 3*x - 5

In either case, when you call f(0) then the expression gets evaluated with value 0 returning -5.在任何一种情况下,当您调用f(0)时,表达式都会被评估为值 0,返回 -5。

2*0**2 + 3*0 - 5 = - 5

The improvement using a custom function over the simple definition of the lambda itself is you can modify the a , b and c parameters.使用自定义 function 对 lambda 本身的简单定义的改进是您可以修改abc参数。

This isn't a lambda specific thing.这不是 lambda 特定的东西。 Its a "closure" and can be done with a regular function also.它是一个“关闭”,也可以使用常规 function 来完成。 In fact, a lambda is just an anonymous function.事实上,一个 lambda 只是一个匿名的 function。 Its it restricted to implementing an expression instead of full python statements, but that's only the case because of python parsing issues.它仅限于实现表达式而不是完整的 python 语句,但这只是由于 python 解析问题的情况。 So, this is the same thing所以,这是同一件事

def build_quadratic_function(a,b,c):
    def inner(x):
        return a*x**2 + b*x+c
    return inner

inner uses variables from the enclosing function. inner使用来自封闭 function 的变量。 When build_quadratic_function returns inner , the current objects in a , b and c are bound to inner .build_quadratic_function返回inner时, abc中的当前对象绑定到inner Later, when inner(someval) is called, those bound objects to a , b and c are used.稍后,当调用inner(someval)时,将使用那些绑定到abc的对象。 x , which is a parameter to inner needs to be supplied on each call. x ,它是inner的一个参数,需要在每次调用时提供。

You can get the inner function once and use it many times with the same values.您可以获得内部 function 一次,并以相同的值多次使用它。

func = build_quadratic_function(1,2,3)
for i in range(10):
    print(func(i))

A lambda function is a small anonymous function. lambda function 是一个小的匿名 function。 (function with no name) (没有名字的函数)

f = build_quadratic_function(2,3,-5)

Till this point, f is equal to the return value of build_quadratic_function , which is another function(lambda in this case)!至此, f 等于build_quadratic_function的返回值,这是另一个函数(在本例中为 lambda)!

f(0) calls the lambda which is waiting f(0)调用正在等待的 lambda

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM