当前位置:首页 » 编程语言 » pythontor

pythontor

发布时间: 2023-07-13 20:30:06

‘壹’ python中支持参数的装饰器要比无参数的多一层什么函数

1. 函数带多个参数
# 普通的装饰器, 打印函数的运行时间
def decrator(func):
def wrap(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
end_time = time.time()
print('运行时间为', end_time-start_time)
return res
return wrap
2. 装饰器带有多个参数
当装饰器带有多个参数的时候, 装饰器函数就需要多加一层嵌套:
比如:
def decrator(*dargs, **dkargs):
def wrapper(func):
def _wrapper(*args, **kargs):
print ("装饰器参数:", dargs, dkargs)
print ("函数参数:", args, kargs)
return func(*args, **kargs)
return _wrapper
return wrapper
为什么被装饰函数体可以传入内层呢?
装饰器函数有多个参数, 需要以
@decrator(1, a=2)
的方式使用, 这时候decrator是已经执行的(因为加了括号), 可以粗略的理解为加载被装饰函数的上的是wrapper, 所以这和普通的装饰器并无差别.
又如flask源码中的:
def route(self, rule, **options):
"""Like :meth:`Flask.route` but for a blueprint. The endpoint for the
:func:`url_for` function is prefixed with the name of the blueprint.
"""
def decorator(f):
endpoint = options.pop("endpoint", f.__name__)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
flask的蓝图route源码中的装饰器, 最内层直接返回return f 并没有多加一层处理的函数, 在无需对被装饰函数进行过多处理的时候这是较为方便的做法. route源码中只是对装饰器参数进行了处理.

热点内容
androidlayoutview 发布:2025-02-08 15:45:01 浏览:620
大货车有哪些安全应急配置 发布:2025-02-08 15:44:55 浏览:537
安卓手机下黎明杀机为什么会闪退 发布:2025-02-08 15:38:27 浏览:488
定位算法源码 发布:2025-02-08 15:36:43 浏览:542
上游服务器异常什么意思 发布:2025-02-08 15:15:46 浏览:175
如何下载油猴脚本并安装 发布:2025-02-08 15:02:12 浏览:596
硬件哪个配置性价比高 发布:2025-02-08 14:47:07 浏览:146
如何去掉仅限自动配置 发布:2025-02-08 14:37:55 浏览:708
压缩空气有啥 发布:2025-02-08 14:26:01 浏览:704
python输入一个数 发布:2025-02-08 14:26:00 浏览:451