a'closure'和'lambda'之间有什么区别? [英] What is the difference between a 'closure' and a 'lambda'?

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

问题描述

有人可以解释吗?我理解他们背后的基本概念,但我经常看到他们互换使用,我很困惑。



现在我们在这里,它们与常规函数有什么不同?

解决方案

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



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

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

这将导致错误,因为 func func 仅在全局环境中关闭。这将工作:

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

因为这里, func anotherfunc 中定义,并且在它们几乎有闭包正确的时候,在python 2.3和更大版本(或者这样的一些数字) ),这意味着它关闭 的anotherfunc 的环境,并可以访问其中的变量。在Python 3.1+中,使用 nonlocal 关键字



另一个重要的一点 - func 将继续关闭 anotherfunc 的环境,即使它不再在 anotherfunc 中求值。此代码也将工作:

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

print anotherfunc(10)()

10。



你注意到,这与 lambda 无关 - 它们是两个不同的p>

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?

解决方案

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 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()

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()

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.

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)()

This will print 10.

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

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

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