python 闭包 装饰器

闭包:是由函数和其他相关的引用环境组合而成的实体。

如果一个函数内部,对在外部作用域的变量进行引用,那么内部函数就被认为是闭包(closure)。

A CLOSURE is a function object that remembers values in enclosing scopes regardless of whether those scopes are still present in memory.

 

>>> def hellocounter(name):

count=[0]

def counter():

count[0]+=1

print "Hello,",name,',',str(count[0])," access"

return counter

 

>>> hello = hellocounter("zxahu")

>>> hello()

Hello, zxahu , 1  access

>>> hello()

Hello, zxahu , 2  access

这里,counter()中调用了外部的变量,所以它这里是闭包

 

__closure__ 属性返回一组cell object,它包含了在闭包环境中的变量,注意,如果变量是引用,那么cell中存储的就是引用,如果是不可变得变量,那么存的是变量

>>> hello.__closure__

(<cell at 0x02DF2FD0: list object at 0x02DF4DA0>, <cell at 0x02E057B0: str object at 0x02E057C0>)

>>> hello.__closure__[0].cell_contents

[2]

>>> hello.__closure__[1].cell_contents

'zxahu'

 

 

装饰器“@decorator

若要增强某函数的功能,但又不希望修改该函数的定义,这种代码运行期间动态增加功能的方式,称为装饰器

def deco(func):
def __decorator():
print "decorator running... prepare function"
func()
print "function done"
return __decorator

@deco
def test():
print "test func running..."

test()

输出:

decorator running... prepare function
test func running...
function done

posted on 2015-08-26 16:21  zxahu  阅读(124)  评论(0编辑  收藏  举报

导航