简体   繁体   English

使单个装饰器成为多个装饰器

[英]Making a single decorator of out multiple

Say, I have something like: 说,我有这样的事情:

@decorator1
@decorator2
def myfunc()
   # ....

How do I declare a new decorator both_decorators which would invoke decorator1 and decorator2 in order, essentially making it an alias for them? 我如何声明一个新的装饰器both_decorators ,它将按顺序调用decorator1decorator2 ,实际上使其成为它们的别名? So that I could write instead: 这样我可以写:

@both_decorators
def myfunc()
   # ....

The idea is to save typing when multiple decorators are used the same way in many cases. 这个想法是在许多情况下以相同的方式使用多个装饰器时可以节省类型。

Simple: 简单:

def both_decorators(func):
    return decorator1(decorator2(func))

because that's all decorators do, really. 因为这实际上是所有装饰者所做的。

Yes, you can. 是的你可以。 Something along the lines of: 类似于以下内容:

def both_decorators(*decs):
    def decorator(dc):
        for dec in reversed(decs):
            dc = dec(dc)
        return dc
    return decorator

Then all you would need to do is add them 然后,您需要做的就是添加它们

@both_decorators(decorator1, decorator2)
def myfunc():
    #something happening here.

Personally I would prefer this, as you can choose which decorator you would want and which not. 我个人比较喜欢这种方式,因为您可以选择所需的装饰器,而不需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM