解决装饰器的参数问题
期望它可以接收任意参数
import time
# 装饰器函数
def cont_time(func):
"""统计时间的装饰器"""
def inner(*args, **kwargs):
start_time = time.time()
print('计时开始。。。')
res = func(*args, **kwargs)
end_time = time.time()
print('计时结束,总共耗时{:.2f}秒'.format(end_time - start_time))
return res
return inner
# 功能函数
@cont_time # 相当于 do_work = cont_time(do_word)
def do_work(name, gender="男"):
"""有耗时的函数"""
print('do_work开始')
time.sleep(1)
print(name, gender)
print('do_work结束')
return 'work is done' # 返回值需要传递
res = do_work("张三", 22)
print(res)
结果
C:\Users\python_hui\Anaconda3\python.exe G:/test/a/1.py
计时开始。。。
do_work开始
张三 22
do_work结束
计时结束,总共耗时1.00秒
work is done
Process finished with exit code 0