Python中的闭包

北慕城南 提交于 2019-12-13 01:09:56

将组成函数的语句和这些语句的执行环境打包在一起时,得到的对象就是闭包。
我们看一个例子
foo.py

12345678910111213141516171819202122232425
x=44def (func):    return func()import foodef bar():    x=13    def hello():        return "hello %s" %x    foo.callf(hello)得到结果为 hello 13在编写惰性求值的代码的时候,闭包是一个很好的选择from urllib import urlopen     def page (url) :         def get() :             return urlopen (url).read()        return get >>>python=page("http://www.python.org") >>>jython=page( "http://www.jython.org") >>>python <function get at 0x9735f0>>>>jython <function get at 0x9737f0>>>>pydata=python() >>>jydata=jython() page()

函数实际上是不执行任何有意义的计算,它只是创建和返回函数get()
如果需要在一个函数中保持某个状态,使用闭包是一种非常高效的行为。

1234567891011
def countdown(n):    def next():        nonlocal n        r=n        n-=1        return r    return nextnext=countdown(10)while True:    v=next()    if not v:break

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!