Python学习笔记——decorator
来源:互联网 发布:sqlserver 完美 卸载 编辑:程序博客网 时间:2024/05/02 12:53
小结:1.请编写一个decorator,能在函数调用的前后打印出'begincall'
和'endcall'
的日志。
def log(f):
@log
def f():
结果:开始前会打印begin call 但是结束后不会有end call。分析原因:在returnf(*args,**kw)语句时对应的f函数就已经返回(执行完毕),而打印'endcall'只在第一次(初始化log(f)的时候)时执行了,而后每次调用f()都不执行该语句。解决办法暂时没找到。
----------------------------------------------------------------------------------------------------------------------------------------
找到了解决办法
val = f(*args,**kw)
print 'end call'
return val
就可以啦!
----------------------------------------------------------------------------------------------------------------------------------------
2.能否写出一个@log
的decorator,使它既支持:
@logdef f(): pass
又支持:
@log('execute')def f(): pass
importfunctools
def log(text):
写的略复杂,没想出来还能不能再精简了。传入参数后先判断实参类型来区别是log(f)还是log('execute')(f),从而确认是三层嵌套还是两层嵌套的装饰器。
- Python学习笔记——decorator
- Python的decorator学习笔记
- Python学习笔记(二) 装饰器decorator
- 模式学习笔记——Decorator/装饰模式
- 设计模式学习笔记(十)——Decorator装饰
- Decorator模式——设计模式学习笔记
- 设计模式学习笔记——Decorator装饰模式
- 设计模式学习笔记——装饰(Decorator)模式
- 设计模式学习笔记(六)—Decorator装饰模式
- python学习--decorator练习
- Python学习笔记(六):decorator装饰器
- python进阶——装饰器Decorator
- python中的decorator学习中......
- Python学习之Decorator详解
- 设计模式笔记——Decorator
- JavaScript设计模式学习——Decorator
- 学习:java设计模式—Decorator模式
- 学习:java设计模式—Decorator模式
- 20150407
- linux学习之--安装一套OCS inventory-ng 环境
- Android 技能树
- Python学习笔记——高阶函数
- 转 time_t tm systemtime 互相转换
- Python学习笔记——decorator
- Spring aop:pointcut--expression--多个execution连接方法
- 基础知识梳理1——范数
- 基础知识梳理2——凸优化与半定规划(…
- 从高维数据中获取低维结构——背景总…
- C#中Split用法~ //作者:不远道人
- HIMPP各功能模块
- 伪元素::after和::before
- 每天linux命令_sudo