python 闭包 装饰器
2015-08-26 16:21
134 查看
闭包:是由函数和其他相关的引用环境组合而成的实体。
如果一个函数内部,对在外部作用域的变量进行引用,那么内部函数就被认为是闭包(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
若要增强某函数的功能,但又不希望修改该函数的定义,这种代码运行期间动态增加功能的方式,称为装饰器
decorator running... prepare function
test func running...
function done
如果一个函数内部,对在外部作用域的变量进行引用,那么内部函数就被认为是闭包(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
相关文章推荐
- python super用法
- python查询mx ns 记录
- Python GUI 以及绘图参考
- python解析ini、conf、cfg文件
- 轻松python文本专题-字符串逐字符反转以及逐单词反转
- 轻松python文本专题-字符串逐字符反转以及逐单词反转
- Isolation forest的python代码实现
- [python] 向指定套接字发送信息
- Python单元测试框架
- Python中函数参数传递问题
- [python] CVE信息大集合
- python列出文件夹下的所有文件
- python decorator 用法
- python中的时间和日期
- 详细记录python的range()函数用法
- Python ->> 第一个Python程序
- python idle 清屏问题的解决
- python __init__和__new__之间的区别
- python wraps装饰器
- python零基础走起