简单讲解Python中的闭包
|
闭包并不是什么新奇的概念,它早在高级语言开始发展的年代就产生了。闭包(Closure)是词法闭包(Lexical Closure)的简称。对闭包的具体定义有很多种说法,这些说法大体可以分为两类: 就像这样: #python 中的闭包 ... def func(data): ... count = [data] ... def wrap(): ... count[0] += 1 ... return count[0] ... return wrap ... ... a = func(1) >>> a() 5: 2 >>> a() 6: 3 def func(x): ... return lambda y :y+x >>> b = func(1) >>> b(1) 7: 2 >>> b(2) 8: 3 >>> print b #这里b是个function 在ruby中是proc <function <lambda> at 0x01AC68F0> def addx(x): ... def adder (y): return x + y ... return adder >>> add8 = addx(8) >>> add8(8) 9: 16 简单说,闭包就是根据不同的配置信息得到不同的结果 python实例 例1
def make_adder(addend):
def adder(augend):
return augend + addend
return adder
p = make_adder(23)
q = make_adder(44)
print p(100)
print q(100)
运行结果: 123 144 分析一下: 再看看运行结果,我们发现,虽然p和q都是make_adder生成的,但是因为配置参数不同,后面再执行相同参数的函数后得到了不同的结果.这就是闭包. 例2
def hellocounter (name):
count=[0]
def counter():
count[0]+=1
print 'Hello,',name,str(count[0])+' access!'
return counter
hello = hellocounter('ma6174')
hello()
hello()
hello()
执行结果 Hello,ysisl,1 access! Hello,2 access! Hello,3 access! 分析一下 UnboundLocalError: local variable 'count' referenced before assignment. 什么意思?就是说conut这个变量你没有定义就直接引用了,我不知道这是个什么东西,程序就崩溃了.于是,再python3里面,引入了一个关键字:nonlocal,这个关键字是干什么的?就是告诉python程序,我的这个count变量是再外部定义的,你去外面找吧.然后python就去外层函数找,然后就找到了count=0这个定义和赋值,程序就能正常执行了. python3 代码
def hellocounter (name):
count=0
def counter():
nonlocal count
count+=1
print 'Hello,str(count[0])+' access!'
return counter
hello = hellocounter('ma6174')
hello()
hello()
hello()
例3
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
print hello()
执行结果 <b><i>hello world</i></b> 简单分析 python里面的好多高级功能,比如装饰器,生成器,列表推到,闭包,匿名函数等,开发中用一下,可能会达到事半功倍的效果!
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
