python学习-装饰器
2014-08-02 17:50
330 查看
#-*- coding:utf-8 -*- import functools def current(): print 'nihao' current() g = current g() #函数有默认字段__name__(2个下划线) print current.__name__ print g.__name__ ''' 装饰器的定义 在不改变某个函数的内部代码的情况下 在执行函数的前后加上一些逻辑 称作装饰器 ''' #举例,在current函数运行前打印一行日志 def log(func): def wrapper(*args,**kw): print 'call %s()'%func.__name__ return func(*args,**kw) return wrapper @log def current2(): print 'nihao' current2() ''' 看例解疑: 当给current2函数加上@log后 会发现current2执行前先打印了call current2() 这是因为装饰器的调用相当于把后面跟的函数放进了 装饰器里面去了.上面执行current2步骤: 1.执行current2(),返回wrapper() 2.执行wrapper(),打印call current2(),得到current2() 3.执行current2(),打印'nihao' ''' #上面的@log定义等同于下面的形式 #current2 = log(current2) current2() print 'current2函数名:' print current2.__name__ #上面的装饰器本身不带参数,为2层嵌套. #如何要带参数,那就要3层嵌套,先获得参数 def logt(text): def log(func): @functools.wraps(func) def wrapper(*args,**kw): print '%s %s():'% (text,func.__name__) return func(*args,**kw) return wrapper return log @logt('execute') def current3(): print 'nihaoa' print '调用装饰器logt:' current3() ''' 上面的写法很容看出来执行的步骤 1.执行current3(),得到log() 然后就跟之前的顺序一样 ''' #@logt定义等同下面的形式 #current3 = logt('execute')(current3) #但是你会发现它打印的信息中有wrapper函数 #而且函数名称也变为了wrapper print '执行经过装饰器改装后的current3:' current3() print 'current3函数名:' print current3.__name__ #这是什么原因,我也不知道#正在理解中 #解决方法是加上这么一句@functools.wraps(func)就解决啦
相关文章推荐
- Python装饰器学习
- Python装饰器学习(九步入门)
- Python学习23:函数装饰器的使用(方法重用)
- python 学习笔记——python 装饰器(一)
- Python装饰器学习
- Python装饰器学习
- Python装饰器学习
- python装饰器学习
- Python装饰器学习
- Python装饰器学习(九步入门)
- Python装饰器学习
- Python装饰器学习(九步入门)
- Python装饰器学习(补充)
- Python装饰器学习
- Python装饰器学习
- python装饰器学习总结
- Python装饰器学习 (附实例)
- 转:Python装饰器学习
- Python装饰器学习(九步入门)
- Python装饰器学习(九步入门) 分类: python学习 2015-03-06 14:26 90人阅读 评论(0) 收藏