decorator 是一个 Python 第三方库,使用该库装饰的函数更符合直觉,代码的逻辑更容易理解
参考资料
decorator官方文档
安装
通过 pipenv 安装:
1
| pipenv install decorator
|
通过 pip3 安装:
1
| pip3 install decorator -i https://pypi.tuna.tsinghua.edu.cn/simple
|
常规装饰器用法
一个装饰器的简单例子
1 2 3 4 5 6 7 8 9 10 11 12
| def deco(func): def wrapper(*args, **kw): print('准备运行任务') func(*args, **kw) print('成功运行任务') return wrapper
@deco def myfunc(): print('开始运行任务')
myfunc()
|
使用 decorator
1 2 3 4 5 6 7 8 9 10 11 12 13
| from decorator import decorator
@decorator def deco(func, *args, **kw): print('准备运行任务') func(*args, **kw) print('成功运行任务')
@deco def myfunc(): print('开始运行任务')
myfunc()
|
func
:被装饰函数
*args, **kw
:可变参数,被装饰函数的原参数
装饰器也可以带参数,这是一个官方示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import time import logging from decorator import decorator
@decorator def warn_slow(func, timelimit=60, *args, **kw): t0 = time.time() result = func(*args, **kw) dt = time.time() - t0 if dt > timelimit: logging.warn('%s took %d seconds', func.__name__, dt) else: logging.info('%s took %d seconds', func.__name__, dt) return result
@warn_slow def preprocess_input_files(inputdir, tempdir): ...
@warn_slow(timelimit=600) def run_calculation(tempdir, outdir): ...
|
func
:被装饰函数
timelimit
:位置参数,并且有默认值
*args, **kw
:可变参数,被装饰函数的原参数