装饰器本质上是一个函数,该函数用来处理其他函数,它可以让其他函数在不需要修改代码的前提下增加额外的功能,装饰器的返回值也是一个函数对象。
1.当没有参数时,如果计算一个程序运行的时间:
def show_time(func):
def wrapper():
start=time.time()
func()
end=time.time()
print("花费了%d秒"%(end-start))
return wrapper
def add():
a=3
time.sleep(1)
print(a)
add=show_time(add)
add()
@符号是装饰器的语法糖,在定义函数的时候使用,避免再一次赋值操作
@show_time
def add():
a=3
time.sleep(1)
print(a)
2.当有参数时:
import time
def show_time(func):
def wrapper(a,b):
start_time=time.time()
func(a,b)
end_time=time.time()
print('spend %s'%(end_time-start_time))
return wrapper
@show_time #add=show_time(add)
def add(a,b):
time.sleep(1)
print(a+b)
add(2,4)
在这里add=show_time(add) 是在获取wrapper这个对象