“闭包"和“lambda"有什么区别? [英] What is the difference between a 'closure' and a 'lambda'?

查看:30
本文介绍了“闭包"和“lambda"有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下?我理解它们背后的基本概念,但我经常看到它们互换使用,我感到困惑.

Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused.

既然我们在这里,它们与常规函数有何不同?

And now that we're here, how do they differ from a regular function?

推荐答案

lambda 只是一个匿名函数 - 一个没有名称定义的函数.在某些语言中,例如 Scheme,它们等价于命名函数.事实上,函数定义被重写为在内部将 lambda 绑定到变量.在其他语言中,例如 Python,它们之间存在一些(相当不必要的)区别,但在其他方面它们的行为方式相同.

A lambda is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.

A closure 是任何关闭环境定义它的函数.这意味着它可以访问不在其参数列表中的变量.示例:

A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. Examples:

def func(): return h
def anotherfunc(h):
   return func()

这会导致错误,因为func 不会关闭 anotherfunc - h 中的环境不明确的.func 只关闭全局环境.这将起作用:

This will cause an error, because func does not close over the environment in anotherfunc - h is undefined. func only closes over the global environment. This will work:

def anotherfunc(h):
    def func(): return h
    return func()

因为在这里,func 是在 anotherfunc 中定义的,并且在 python 2.3 和更高版本(或类似这样的数字)中,当它们几乎闭包正确(变异仍然不起作用),这意味着它关闭 anotherfunc 的环境并且可以访问其中的变量.在 Python 3.1+ 中,使用 nonlocal 时,突变也起作用 关键字.

Because here, func is defined in anotherfunc, and in python 2.3 and greater (or some number like this) when they almost got closures correct (mutation still doesn't work), this means that it closes over anotherfunc's environment and can access variables inside of it. In Python 3.1+, mutation works too when using the nonlocal keyword.

另一个重点 - func 将继续关闭 anotherfunc 的环境,即使它不再在 anotherfunc 中被评估.此代码也适用:

Another important point - func will continue to close over anotherfunc's environment even when it's no longer being evaluated in anotherfunc. This code will also work:

def anotherfunc(h):
    def func(): return h
    return func

print anotherfunc(10)()

这将打印 10.

正如您所注意到的,这与 lambda 无关 - 它们是两个不同(尽管相关)的概念.

This, as you notice, has nothing to do with lambdas - they are two different (although related) concepts.

这篇关于“闭包"和“lambda"有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆