Python: return 其他装饰器的装饰器

Python: Decorator which return other decorator

我有 2 个 classes 用作装饰器

class A:
    """This is a decorator"""
    pass

class B:
    """This is also a decorator"""
    pass

还有第三个 class 我想 return A 或 B

class C:
    def a(func):
        return A

    def b(func):
        return B


@C.a
def some_func(some_arg):
    pass

@C.b
def other_func(some_arg):
    pass

是否可以这样,如果可以如何实现?

更新: 问题是在创建装饰器时,'call' 在创建期间被执行。我想访问一些稍后设置的配置。所以我基本上想做的是 return 包装器,return 包装器。

class C:
    def __call__(func):
        def wrapper(*args, **kwargs):
             # Do something with global data
             return func(*args, **kwargs)
        return wrapper

如果你想让你的代码正常工作,你需要做的就是将你的方法更改为属性:

class C:
    a = A
    b = B

不过,这是否是个好主意值得怀疑。如果你想要一个装饰器来做两种不同的事情之一,二阶装饰器(即返回装饰器的函数)可能更合适。

您可以通过将 class C 更改为这样来使它工作。

class C:
    def a(func):
        return A(func)

真正归结为了解装饰器只是一个语法快捷方式。

@dec
def f():
    pass

完全相同:

def f():
    pass
f = dec(f)