- get新技能啦 :
简单的装饰器:
def timmer(func):
def inner():
start_time=time.time()
func()
end_time=time.time()
print('程序执行时长:',end_time-start_time)
return inner
@timmer #func1=timmer(func1)
def func1():
time.sleep(2)
print('in func1')
# func1=timmer(func1)
func1()
带参数的装饰器:
传入一个参数:
def timmer(func):
def inner(a):
start_time=time.time()
func(a)
end_time=time.time()
print('程序执行时长:',end_time-start_time)
return inner
@timmer
def func1(a):
time.sleep(2)
print('in func1',a)
func1(1)
#动态传入参数
def timmer(func):
def inner(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs)
end_time=time.time()
print('程序执行时长:',end_time-start_time)
return inner
@timmer
def func1(a):
time.sleep(2)
print('in func1',a)
@timmer
def func2(a,b):
time.sleep(2)
print('in func2',a,b)
func2(1,2)
带返回值:
def timmer(func):
def inner(*args,**kwargs):
start_time=time.time()
ret=func(*args,**kwargs)
end_time=time.time()
print('程序执行时长:',end_time-start_time)
return ret
return inner
@timmer
def func1(a):
time.sleep(2)
print('in func1',a)
@timmer
def func2(a,b):
time.sleep(2)
print('in func2',a,b)
func2(1,2)
装饰器进阶:
def wrapper(f):
def inner(*args,**kwargs):
print("被装饰函数前要做的事情")
ret=f(*args,**kwargs)
print("被装饰函数后要做的事情")
return ret
return inner
@wrapper #===>holiday=wrapper(holiday)
def holiday(day):
print("全体放假%s天" %(day))
return "好好工作,会涨工资的"
a=holiday(3)
print(a)
本文摘自:
https://www.cnblogs.com/Eva-J/articles/7194277.html#_label4