将组成函数的语句和这些语句的执行环境打包在一起时,得到的对象就是闭包。
我们看一个例子
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 |
来源:https://www.cnblogs.com/lijianming180/p/12032694.html