将组成函数的语句和这些语句的执行环境打包在一起时,得到的对象就是闭包。
我们看一个例子
foo.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
x=44
def (func): return func()
import foo def bar(): x=13
def hello():
return "hello %s" %x foo.callf(hello) 得到结果为 hello 13
在编写惰性求值的代码的时候,闭包是一个很好的选择
from urllib import urlopen def page (url) : def get() : 大专栏 Python中的闭包 class="keyword">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()
如果需要在一个函数中保持某个状态,使用闭包是一种非常高效的行为。
1 2 3 4 5 6 7 8 9 10 11
|
def countdown(n): def next():
nonlocal n r=n n-=1
return r return next next=countdown(10)
while True: v=next() if not v:break
|