gpt4 book ai didi

python - 如何扩展库的装饰器?

转载 作者:太空宇宙 更新时间:2023-11-04 10:17:30 27 4
gpt4 key购买 nike

我想扩展一个库的装饰器。我知道我可以调用两个装饰器:

@my_decorator
@lib_decorator
def func():
pass

但我想避免每次都必须将 @lib_decorator 传递给每个函数。我希望我的装饰器使用 lib_decorator 自动装饰 func()。我怎样才能做到这一点?它们可以嵌套吗?

最佳答案

您可以将库的装饰器合并到您的装饰器中。对于简单的、无参数的装饰器,它相当简单:

def my_decorator():
@lib_decorator # <--- Just include the lib's decorator here
def inner:
func(*args, **kwargs)
return inner

对于有参数的装饰器来说有点棘手。请记住,您的装饰器正在用最内层的函数替换装饰函数。这就是你需要装饰的那个。所以如果你用 args 调用你的装饰器,例如

@my_decorator(arg)
def func():
pass

然后用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

或者,使用装饰器函数的 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

关于python - 如何扩展库的装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34443271/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com