不用装饰器的写法:
import time
def i_can_sleep():
time.sleep(3)
start_time = time.time()
i_can_sleep()
end_time = time.time()
print("函数运行了 %s 秒:" %(end_time-start_time))
如果需要统计很多次i_can_sleep(),每次都需要写很多次 start_time = time.time(),end_time = time.time(),这样的语句。当用了装饰器之后就可以直接调用 i_can_sleep()。
用装饰器的写法:
import time
def timer(func):
def wrapper():
start_time = time.time()
func()
stop_time = time.time()
print("运行时间是 %s 秒" % (stop_time-start_time))
return wrapper
@timer
def i_can_sleep():
time.sleep(3)
i_can_sleep()
装饰器的使用:
def tips(func):
def nei(a,b):
print("start")
func(a,b)
print("stop")
return nei
@tips
def add(a,b):
print(a+b)
@tips
def sub(a,b):
print(a-b)
print(add(4,5))
print(sub(4,5))
def new_tips(argv):
def tips(func):
def nei(a, b):
print("start %s %s" %(argv,func.__name__))
func(a, b)
print("stop")
return nei
return tips
@new_tips('add')
def add_func(a,b):
print(a+b)
@new_tips('sub')
def sub_func(a,b):
print(a-b)
print(add_func(4,5))
print(sub_func(4,5))
|