装饰器通过函数来定义,用来装饰函数

装饰器的结构为高阶函数和内嵌函数

装饰器不改变被装饰函数的源代码和运行方式

如何实现这个效果呢?

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR" import time def timer(func): #定义一个装饰器
def deco():
start_time = time.time()
func()
stop_time = time.time()
print("the run time is %s"%(stop_time-start_time))
return deco def test1():
time.sleep(3)
print('in the test1') test1 = timer(test1)
test1()

既没有改变被装饰函数的源代码,也没有改变它的运行方式

运行

这么写有些复杂,可以直接在函数前调用装饰器

调用装饰器的格式为:@装饰器名

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR" import time def timer(func): #定义一个装饰器
def deco():
start_time = time.time()
func()
stop_time = time.time()
print("the run time is %s"%(stop_time-start_time))
return deco @timer #相当于test1 = timer(test1)
def test1():
time.sleep(3)
print('in the test1') test1()

运行

执行过程:

先走test1函数前的装饰器timer(),然后在timer()函数内走函数deco(),记录下start_time,然后deco()函数调用函数test1(),然后执行完函数test1()后,记录下stop_time,最后计算时间并打印

虽然装饰器不会修改被装饰函数的源代码和运行方式,但是不能直接返回函数的返回值

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR" import time def timer(func): #定义一个装饰器
def deco():
start_time = time.time()
func()
stop_time = time.time()
print("the run time is %s"%(stop_time-start_time))
return deco @timer #test1 = timer(test1)
def test1():
time.sleep(3)
print('in the test1')
return "test1" print(test1())

运行结果

打印的返回值为None,因为这个返回值为装饰器里的内嵌函数的返回值

如果需要打印被装饰函数的返回值的话,需要在装饰器里的内嵌函数中返回

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR" import time def timer(func): #定义一个装饰器
def doc():
start_time = time.time()
func()
stop_time = time.time()
print("the run time is %s"%(stop_time-start_time))
return func()
return doc @timer #test1 = timer(test1)
def test1():
time.sleep(3)
print('in the test1')
return "test1" print(test1())

运行结果

最新文章

  1. PHP中遍历XML之SimpleXML
  2. 如何只用CSS做到完全居中
  3. BZOJ3515 : EvenPaths
  4. Android VideoView播放视频
  5. iOS 获得指定文件夹下的指定格式文件
  6. SVN-钩子祥解
  7. 移动开发Html 5前端性能优化指南
  8. js实现堆排序
  9. NOI 191钉子和小球.cpp
  10. css学习之color: window和color: currentColor
  11. Phaser是一款专门用于桌面及移动HTML5 2D游戏开发的开源免费框架
  12. [Unity]C#.数据类型总结
  13. JS实现轻量级计算器
  14. Redis客户端ServiceStack.Redis的简单使用
  15. WebApi-2 自定义路由与默认路由
  16. 转 Singleton clr via c#3
  17. 论文笔记:Auto-ReID: Searching for a Part-aware ConvNet for Person Re-Identification
  18. DeepLearning.ai-Week4-Deep Learning & Art: Neural Style Transfer
  19. FMS Dev Guide学习笔记(权限控制)
  20. 【Oracle】使用dbms_job包创建Oracle定时任务

热门文章

  1. HBase-协处理器详解及实现
  2. Qt QThread 线程创建,线程同步,线程通信 实例
  3. SPOJ375 QTREE - Query on a tree
  4. org.apache.http.NoHttpResponseException: XX.XX.XX.XX:80 failed to respond
  5. Tensorflow搭建神经网络及使用Tensorboard进行可视化
  6. webdriver处理鼠标右键菜单栏
  7. java时间戳转换
  8. 2018.7.2 AK22 不良品分析
  9. Codeforces Round #266 (Div. 2)B(暴力枚举)
  10. Linux命令学习(18):route命令