最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python带参数的装饰器运行原理代码解析
时间:2020-06-09 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下Python带参数的装饰器运行原理代码解析,代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
关于装饰器的理解,特别像《盗梦空间》中的进入梦境和从梦境出来的过程,一层一层的深入梦境,然后又一层一层的返回,被带入梦境的是被装饰的函数,装饰器就是使人入梦的工具。
上代码:
from functools import wraps def decorator_with_argument(argument=''): def outer(func): message = argument + func.__name__ @wraps(func) def inner(*args, **kwargs): print(message) print('This is inner function running') return func(*args, **kwargs) return inner return outer
以上是装饰器的部分。
接下来,是带参数的装饰器:
@decorator_with_argument("Decorator's argument + ") def pfunc(arg='default'): print('This is pfunc running') print(f'This " {arg} " is from pfunc argument')
最后,函数的运行:
pfunc("pfunc's argument")
函数本身也是带参数的。输出结果如下:
Decorator's argument + pfunc
This is inner function running
This is pfunc running
This " pfunc's argument " is from pfunc argument
Process finished with exit code 0
下图是关于梦境的具体图示:
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27