如何装饰类或静态方法

bgu*_*ach 6 python decorator class-method

我正在编写一个通用类装饰器,它需要将装饰器应用于每个方法。我的第一个方法是这样的:

def class_decorator(cls):
    for name, member in vars(cls).items():
        # Ignore anything that is not a method
        if not isinstance(member, (types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod)):
            continue

        setattr(cls, name, method_decorator(member))

    return cls
Run Code Online (Sandbox Code Playgroud)

装饰器本身并不是很重要。看起来像这样:

def method_decorator(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        # do something
        return fn(*args, **kwargs):

    return wrapper
Run Code Online (Sandbox Code Playgroud)

一旦我测试了它,我遇到了一个问题,这不适用于静态或类方法,并且引发以下错误functools.wraps

AttributeError: 'classmethod' object has no attribute '__module__'
Run Code Online (Sandbox Code Playgroud)

是的,classmethod或者staticmethods不是普通函数,甚至不是可调用函数。一般来说,如果你需要装饰一个classmethod,你首先应用你的装饰器,然后应用classmethod装饰器,但由于这是一个类装饰器,我无法影响装饰器的顺序。

对此有什么好的解决办法吗?

bgu*_*ach 11

经过一段时间的研究,我发现了一个比 SO 中其他方法更好的解决方案。也许这对某人有帮助。

基本上这个想法如下:

  • 检测属于类或静态方法的成员
  • 获取包含在这些方法中的函数对象
  • 将装饰器应用到该函数
  • 将修饰函数包装在classmethodorstaticmethod实例中
  • 再次将其存储在类中

代码如下所示:

def class_decorator(cls):
    for name, member in vars(cls).items():
        # Good old function object, just decorate it
        if isinstance(member, (types.FunctionType, types.BuiltinFunctionType)):
            setattr(cls, name, method_decorator(member))
            continue

        # Static and class methods: do the dark magic
        if isinstance(member, (classmethod, staticmethod)):
            inner_func = member.__func__
            method_type = type(member)
            decorated = method_type(method_decorator(inner_func))
            setattr(cls, name, decorated)
            continue

        # We don't care about anything else

    return cls
Run Code Online (Sandbox Code Playgroud)