首页 > 编程语言 > 详细

Python中的闭包

时间:2019-12-13 09:16:39      阅读:93      评论:0      收藏:0      [点我收藏+]

将组成函数的语句和这些语句的执行环境打包在一起时,得到的对象就是闭包。
我们看一个例子
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

Python中的闭包

原文:https://www.cnblogs.com/lijianming180/p/12032694.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!