python中装饰器的简单用法
来源:互联网 发布:在淘宝卖宠物用品 编辑:程序博客网 时间:2024/05/23 00:00
装饰器在python中扮演着很重要的作用,例如插入日志等,装饰器可以为添加额外的功能同时又不影响业务函数的功能。
比如,运行业务函数fun()同时打印运行花费的时间
1,运行业务函数fun()同时打印运行花费的时间
import time
def dec(fun):
start = time.time()
fun()
end = time.time()
a = end - start
print a
def myfun():
print 'run myfunction'
dec(myfun)
运行结果
(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.00108599662781
但是每次运行myfun都要调用dec,下面作下变动解决这个问题
2,
import time
def dec(fun):
def wrap():
start = time.time()
fun()
end = time.time()
a = end - start
print a
return wrap
def myfun():
print 'run myfunction'
myfun=dec(myfun)
myfun()
运行结果:
(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.00122618675232
这个装饰器dec就实现了,并且不影响函数myfun功能
3,装饰器@符
import time
def dec(fun):
def wrap():
start = time.time()
fun()
end = time.time()
a = end - start
print a
return wrap
@dec
def myfun():
print 'run myfunction'
myfun()
结果
(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.000470876693726
使用了@后,就不用给myfun重新赋值了
@dec就相当于myfun=dec(myfun)
- python中装饰器的简单用法
- python中@property装饰器的用法
- python中@property装饰器的用法
- Python装饰器的用法
- Python中@的用法(Decorator:装饰器)
- python装饰器的十种用法
- python装饰器,自己实现一个简单的装饰器
- python装饰器,自己实现一个简单的装饰器
- python装饰器,自己实现一个简单的装饰器
- python的装饰器的简单案例
- 关于python的装饰器简单实用
- 简单地理解 Python 的装饰器
- 简单地理解 Python 的装饰器
- 简单地理解 Python 的装饰器
- Python装饰器(decorator)用法
- Python中装饰器
- python 中装饰器
- python装饰器的4中类型:函数装饰函数、函数装饰类、类装饰函数、类装饰类
- VMware vSphere Client WIN10安装问题
- 混淆矩阵
- java中嵌入javascript
- Mysql 存储过程小例子
- 面试题之树中两个节点的最低公共祖先节点
- python中装饰器的简单用法
- 服务器搭建
- Lab_6
- linux 文件测试运算符
- 【UGUI】无限循环列表和InputField.onValueChanged 事件
- ThinkPHP 框架下支付宝支付
- java中import作用详解
- Linux之shell脚本编程实例--遍历所有文件,并按月份打成zip包
- 引子1-输出信息新办法