装饰器

装饰器是用来处理其他函数的函数,主要作用是在不修改原有函数的情况下添加新的功能,装饰器的返回值也是一个函数对象。

简单的装饰器

 import time

 def show_time(f):
def inner():
start = time.time()
f()
end = time.time()
print('time: %s'%(end-start))
return inner @show_time
def fun1():
print('hello')
time.sleep(1) fun1()
#输出
#hello
#time: 1.000274896621704

其中@show_time的意思是 fun1 = showtime(fun1) ,作用是在执行原函数add()时,把执行的代码转为inner()函数中的代码。

带参数的被装饰函数

如果被装饰的函数带有参数则装饰函数要带上参数。

参数个数确定时:

 import time

 def show_time(f):
def inner(a,b):
start = time.time()
f(a,b)
end = time.time()
print('time: %s'%(end-start))
return inner @show_time
def fun1(x,y):
print(x+y)
time.sleep(1) fun1(1,2)
#输出
#3
#time: 1.0007870197296143

参数个数不确定时:

 import time

 def show_time(f):
def inner(*args,**kwargs):
start = time.time()
f(*args,**kwargs)
end = time.time()
print('time: %s'%(end-start))
return inner @show_time
def fun1(*args,**kwargs):
sum = 0
for i in args:
sum+=i
print(sum)
time.sleep(1) fun1(1,2,3,4,5)
#输出
#15
#time: 1.0009024143218994

带参数的装饰器

import time
def judge(flag = 'False'):
def show_time(f):
def inner(*args,**kwargs):
if flag == 'True':
start = time.time()
f(*args,**kwargs)
end = time.time()
print('time: %s'%(end-start))
else:
f(*args, **kwargs)
return inner
return show_time @judge('True')
def add(*args,**kwargs):
sum = 0
for i in args:
sum+=i
print(sum)
time.sleep(1) @judge()
def multiple(*args,**kwargs):
sum = args[0]
for i in args:
sum*=i
print(sum)
time.sleep(1) add(1,2,3,4,5)
multiple(1,2,3,4,5)
#输出
#15
#time: 1.0006871223449707
#120

装饰器的语法允许我们在调用时,提供其它参数,比如当@judge()参数为默认的False时,不输出消耗时间了,当@judge()参数为True时,输出了消耗时间。这样实际上是在原有的装饰器上再加了一层,当我 们使用@judge(‘True’)调用的时候,Python能够发现这一层的封装,并把参数传递到装饰器的环境中。

最新文章

  1. 记录Tomcat7.x热部署配置过程
  2. Sharepoint学习笔记—习题系列--70-573习题解析 -(Q28-Q31)
  3. JQuery基础教程:入门
  4. 使用eclipse搭建嵌入式开发环境
  5. 鼠标聚焦到Text输入框时,按回车键刷新页面原因及解决方法
  6. poj 1094 Sorting It All Out(图论)
  7. 实验吧Web-FALSE
  8. 游戏客户端嵌入页面出白边bug
  9. 解析SS、SP、BP寄存器
  10. 移动端web总结
  11. dede被注入后台提示用户名不存在解决方法
  12. MySQL Server 的安装方法及简要步骤
  13. Golang Go Go Go part2:变量及常量声明
  14. 转STM32官方固件库简介
  15. 流媒体技术笔记(DarwinStreamingServer相关)
  16. nginx解析漏洞,配置不当,目录遍历漏洞环境搭建、漏洞复现
  17. spring 4.0下集成webservice
  18. 解决android studio项目中Failded to sync Gradle project 'XXXX' Cause:failed to find target with hash string 'android-16'问题
  19. vim常用快捷汇总
  20. .NET Core On Liunx环境搭建之MongoDB

热门文章

  1. font-failmly字体对应
  2. Java 8-接口的默认方法和静态方法
  3. SSM衍生的配置文件
  4. [原创]HBase学习笔记(2)- 基本操作
  5. Ubuntu16.04测网速
  6. vue中的slot(插槽)
  7. S/4 HANA中发票输出切换回NAST
  8. ABAP术语-XML
  9. My SQL常用操作汇总
  10. jqGrid 分页