drs*_*drs 9 python decorator python-decorators
我想扩展图书馆的装饰器。我知道我可以调用两个装饰器:
@my_decorator
@lib_decorator
def func():
pass
Run Code Online (Sandbox Code Playgroud)
但我想避免@lib_decorator每次都必须传递给每个函数。我希望我的装饰器自动func()使用lib_decorator. 我怎样才能做到这一点?它们可以嵌套吗?
drs*_*drs 10
您可以将 lib 的装饰器合并到您的装饰器中。对于简单的、无参数的装饰器,它相当简单:
def my_decorator():
@lib_decorator # <--- Just include the lib's decorator here
def inner:
func(*args, **kwargs)
return inner
Run Code Online (Sandbox Code Playgroud)
对于有参数的装饰器来说,这有点棘手。请记住,您的装饰器正在用最内部的函数替换装饰函数。所以这就是你需要装饰的地方。因此,如果您使用 args 调用装饰器,例如
@my_decorator(arg)
def func():
pass
Run Code Online (Sandbox Code Playgroud)
然后用lib装饰器装饰内部函数:
def my_decorator(arg):
def wrapper(func):
@lib_decorator # <--- Just include the lib's decorator here
def inner(*args, **kwargs):
func(*args, **kwargs)
return inner
return wrapper
Run Code Online (Sandbox Code Playgroud)
或者,使用class装饰器函数的形式:
class my_decorator():
def __init__(self, arg):
pass
def __call__(self, func):
@lib_decorator # <--- Just include the lib's decorator here
def inner(*args, **kwargs):
func(*args, **kwargs)
return inner
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2723 次 |
| 最近记录: |