什么是Python中的" lambda绑定"?

时间:2020-03-06 15:00:32  来源:igfitidea点击:

我了解Python中的lambda函数是什么,但是我无法通过搜索Python文档来找到" lambda绑定"的含义。
一个链接来阅读它会很好。
一个简单的解释示例会更好。
谢谢你。

解决方案

我们在哪里看到过该短语?

Python中的"绑定"通常是指变量名最终指向特定对象的过程,无论是通过赋值还是通过参数传递或者其他某种方式,例如:

a = dict(foo="bar", zip="zap", zig="zag") # binds a to a newly-created dict object
b = a # binds b to that same dictionary

def crunch(param):
  print param

crunch(a) # binds the parameter "param" in the function crunch to that same dict again

因此,我想" lambda绑定"是指将lambda函数绑定到变量名称的过程,或者可能是将其命名参数绑定到特定对象的过程? http://docs.python.org/ref/naming.html的《语言参考》中对绑定有一个很好的解释。

一,一般定义:

When a program or function statement
  is executed, the current values of
  formal parameters are saved (on the
  stack) and within the scope of the
  statement, they are bound to the
  values of the actual arguments made in
  the call. When the statement is
  exited, the original values of those
  formal arguments are restored. This
  protocol is fully recursive. If within
  the body of a statement, something is
  done that causes the formal parameters
  to be bound again, to new values, the
  lambda-binding scheme guarantees that
  this will all happen in an orderly
  manner.

现在,在这里的讨论中有一个出色的python示例:

" ...对于x来说只有一个绑定:执行x = 7只会改变预先存在的绑定中的值。这就是为什么

def foo(x): 
   a = lambda: x 
   x = 7 
   b = lambda: x 
   return a,b

返回两个均返回7的函数;如果在x = 7之后有一个新的绑定,则这些函数将返回不同的值[当然,假设我们不调用foo(7)。还假设nested_scopes] ......"

我从未听说过该术语,但一个解释可能是用于将值直接分配给lambda参数的"默认参数" hack。使用Swati的示例:

def foo(x): 
    a = lambda x=x: x 
    x = 7 
    b = lambda: x 
    return a,b

aa, bb = foo(4)
aa() # Prints 4
bb() # Prints 7