标签:wrap port decorator alt func 装饰器 传递 参数 div
import time
def show_time(f):
def inner(a, b):
start = time.time()
f(a, b)
end = time.time()
print(‘spend %s‘ % (end - start))
return inner
@show_time # add = show_time(add)
def add(a, b):
print(a + b)
time.sleep(1)
add(3, 4)
import time
import functools
def log(func):
@functools.wraps(func)
def wapper():
print(‘%s‘ % func.__name__)
func()
return wapper
@log
def now():
print(time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime()))
2018-04-27 21:56:56
now
functools.wraps 相当于写 wapper.__name__ = now.__name__
不然结果会成为
import time
import functools
def log(func):
# @functools.wraps(func)
def wapper():
print(‘%s‘ % func.__name__)
func()
return wapper
@log
def now():
print(time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime()))
now()
print(now.__name__)
2018-04-27 21:58:32
wapper
装饰器传递参数 如下例
whn-now
2018-04-27 22:07:48
标签:wrap port decorator alt func 装饰器 传递 参数 div
原文地址:https://www.cnblogs.com/thyh/p/8964837.html