Python中的装饰器
来源:互联网 发布:迅雷cdn 知乎 编辑:程序博客网 时间:2024/05/17 03:42
** 该篇由之前写的python装饰器介绍改变格式而来。
python中装饰器是一个很神奇的功能,可以给我们带来许多意想不到的简便。
装饰器本身是一个python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。
装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以剥离出大量与函数功能本身无关的雷同代码并继续重用。
概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。
其实就是分别将要运行的函数,和要运行的函数的参数分别作为参数(有点绕),传递到另外两个函数中去,两外两个函数作为out包装函数和inner包装函数对要运行的函数进行修饰,
伪代码大概是这个样子的:
函数1(要装饰的函数): 函数2(要装饰的函数的参数): 要装饰的函数()=== 要调用的函数在此调用 返回函数2
拆解讲解如下,注意区别:
1.
def myDecorator(function): def statsticTime(): import time start = time.clock() print 'start at: ', start function() end = time.clock() print 'end at: ', end return statsticTime
此时使用:
@myDecoratordef a(): print 'i love China' return 'i love Python'
运行:a():
start at: 1828.02588511i love Chinaend at: 1828.02606038
2.
def myDecorator(function): def statsticTime(): import time start = time.clock() print 'start at: ', start function() end = time.clock() print 'end at: ', end return statsticTime()@myDecoratordef a(): print 'i love China' return 'i love Python'
此时直接会有输出:
start at: 2110.53246682i love Chinaend at: 2110.53259472
3.
def myDecorator(function): def statsticTime(): import time start = time.clock() print 'start at: ', start function end = time.clock() print 'end at: ', end return statsticTime@myDecoratordef a(): print 'i love China' return 'i love Python'
a()
输出:
start at: 2288.03029055end at: 2288.03034266
4.
def myDecorator(function): def statsticTime(*args,**kwargs): import time start = time.clock() print 'start: ', start function(*args,**kwargs) end = time.clock() print 'end: ', end print 'end - start: ', end - start return function(*args, **kwargs) return statsticTime@myDecoratordef a(): print 'i am the world' return 'i love u'
运行: a()
输出:
start: 2382.26522127i am the worldend: 2382.26529666end - start: 7.53977528802e-05i am the worldout:'i love u'
1 0
- Python中的装饰器
- python中的装饰器
- python中的装饰器
- python中的装饰器
- Python中的装饰器
- Python中的装饰器
- python中的装饰器
- python中的装饰器
- python中的装饰器
- Python中的装饰器
- Python中的装饰器
- python中的装饰器
- Python中的装饰器
- Python中的装饰器
- Python 中的装饰器
- python中的装饰器
- Python中的装饰器
- python中的装饰器
- 欢迎使用CSDN-markdown编辑器
- OpenStack 和 Ceph 集成
- sdut 2161 Simple Game(山东省第二届acm省赛A题)(博弈论Nim+Bush?)
- H265(HEVC) nal 单元头介绍及rtp发送中的fu分组发送详解
- Problem B: 大整数的加法运算
- Python中的装饰器
- 为什么在主线程的Looper.looper死循环不会卡死
- Revit开发自定义警告
- win7(64位)Python2.7.13+opencv2.4.23
- Android HTTPS中间人劫持漏洞浅析
- 关于idea15新建的maven项目的tomcat没有artifact以及测试tomcat报404错误
- Unity lua内存泄漏与性能检测
- IE8不支持rgba()的处理方法
- test