装饰器概念
用与拓展原来函数功能的一种函数, 这个函数的特殊之处在于它的返回值是一个函数,使用python装饰器的好处就是在不用更改原函数的代码前提下给函数增加新的功能。
这是一段最开始的代码
import time
def func():
print("hello")
time.sleep(1)
print("world")
想在记录下这个函数的执行总时间,我们可以直接在原函数上直接修改
>>> import time
>>> def func():
... startTime = time.time()
... print("hello")
... time.sleep(1)
... print("world")
... endTime = time.time()
... msecs = (endTime - startTime)*1000
... print("time is %d ms" %msecs)
如果这是公司的核心代码是不允许直接修改函数代码的, 这是时候可以使用装饰器了。
>>> import time
>>> def deco(func):
... def wrapper():
... startime = time.time()
... func()
... endtime = time.time()
... msecs = (endtime-startime)*1000
... print("time is %d ms" %msecs)
... return wrapper
@deco
def func():
print("hello")
time.sleep(1)
print("world")
if __name__ == '__main__':
f = func
f()
这里的deco函数就是一个装饰器, 它的参数是一个函数, 然后返回值也是一个函数。
其中作为参数的这个函数func()就在返回函数wrapper()的内部执行。然后在函数func()前面加上@deco,func()函数就相当于被注入了计时功能,现在只要调用func(),它就已经变身为“新的功能更多”的函数了。
带有参数的装饰器
import time
def deco(func):
def wrapper(a,b):
startTime = time.time()
func(a,b)
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
return wrapper
@deco
def func(a,b):
print("hello,here is a func for add :")
time.sleep(1)
print("result is %d" %(a+b))
if __name__ == '__main__':
f = func
f(3,4)
#func()
多个参数
import time
def deco(func):
def wrapper(*args, **kwargs):
startime = time.time()
func(*args, **kwargs)
endtime = time.time()
msecs = (endtime - startime)*1000
print("time is %d ms" % msecs)
return wrapper
@deco
def func(a, b):
print("hello, here is a func for add :")
time.sleep(1)
print("result is %d" %(a+b))
@deco
def func2(a, b, c):
print("hello, here is a func for add : ")
time.sleep(1)
print("result is %d" %(a+b+c))
if __name__ == "__main__":
f = func
func2(3, 4, 5)
f(3, 4)
多个装饰器
import time
def deco01(func):
def wapper(*args, **kwargs):
print("this is deco01")
startime = time.time()
func(*args, **kwargs)
endtime = time.time()
msecs = (endtime-startime)
print("time is %d ms" %msecs)
print("deco01 end here")
return wapper
def deco02(func):
def wrapper(*args, **kwargs):
print("this is deco02")
func(*args, **kwargs)
print("deco02 end here")
return wrapper
@deco01
@deco02
def func(a, b):
print("hello, here is func for add :")
time.sleep(1)
print("result is %d" %(a+b))
if __name__ == "__main__":
f = func
f(3, 4)
结果:
this is deco01
this is deco02
hello,here is a func for add :
result is 7
deco02 end here
time is 1003 ms
deco01 end here
多个装饰器执行的顺序就是从最后一个装饰器开始,执行到第一个装饰器,再执行函数本身。
参考博客:
https://blog.csdn.net/xiangxianghehe/article/details/77170585
这篇博客将的很详细:
https://blog.csdn.net/appleyk/article/details/77412961
网友评论