这里需要理解装饰器模式, 装饰者与被装饰者实现相同接口.
import time
def timer(func):
def wrapper():
start_time = time.time()
func() # 调用
stop_time = time.time()
print('spend %s sec' % (stop_time-start_time))
return wrapper()
@timer # 将该函数传递给 timer 函数
def i_can_sleep():
# 模拟耗时操作
time.sleep(3)
# 输出
spend 3.0012357234954834 sec
- 带参数
def tips(func):
def nei(a, b):
print('start')
func(a, b)
print('stop')
return nei
@tips
def add(a, b):
print(a+b)
add(4, 5)
# 输出
start
9
stop
- 带参数的装饰器
def new_tips(argv):
print('argv:', argv)
def tips(func):
def nei(a, b):
print('start, name: %s' % func.__name__)
func(a, b)
print('stop')
return nei
return tips
# 带参数的装饰器, 猜测先把参数传递给 new_tips,
# 然后根据参数来选择内部装饰器 (比如 tips),
# 选好之后再把被装饰函数 (add) 传递给 tips.
@new_tips('add_module')
def add(a, b):
print(a+b)
add(4, 5)
# 输出
argv: add_module
start, name: add
9
stop