【发布时间】:2021-03-19 20:52:27
【问题描述】:
我有一个这样的装饰器:
def foo(func):
"""Will print the args and kwargs of a func"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('Do I have args?')
print(args, kwargs, sep='\n')
return func(*args, **kwargs)
return wrapper
还有这样的“装饰师”:
def add_checks(*decorators):
"""Adds decorators to a func"""
def check(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# how do I add here the `*decorators`?
return func(*args, **kwargs)
return wrapper
return check
如何通过字符串添加装饰器?所以它是这样的:
@add_checks('foo')
def bar(a, b, c=1):
return (a * b) / c
print(bar(5, 2, c=5))
>>> Do I have args?
>>> [5, 2]
>>> {'c': 5}
>>> 2
【问题讨论】:
-
您是否有理由要对装饰器进行字符串索引,而不仅仅是使用内联函数引用?
标签: python python-3.x python-decorators