【问题标题】:python decorator for class method and static method?类方法和静态方法的python装饰器?
【发布时间】:2017-07-13 01:51:09
【问题描述】:

我正在尝试为实例方法编写一个装饰器,如下:

from functools import wraps

def plus_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        return 1 + f(*args, **kwargs)
    return wrapper

@plus_decorator
def return_i(i):
    return i

class A(object):
    @plus_decorator
    def return_i(self, i):
        return i

    @plus_decorator
    @classmethod
    def return_i_class(cls, i):
        return i

    @plus_decorator
    @staticmethod
    def return_i_static(i):
        return i

if __name__ == '__main__':
    print return_i(1)
    a = A()
    print a.return_i(1)
    print A.return_i_class(1)
    print A.return_i_static(1)

但是却弹出错误:

AttributeError: 'classmethod' object has no attribute '__module__'

我想知道为什么装饰器在 classmethodstaticmethod 上不起作用。我认为装饰器大多只是将它接收到的所有参数传递给包装器,并且只修改结果。如何修改装饰器以使其适用于 classmethodstaticmethod

【问题讨论】:

  • 您的呼叫站点是什么样的?
  • 这很好用。您没有创建 A() 的实例来调用它,例如a = A(); a.return_i(1)。或许你还需要@classmethod
  • 糟糕。我遇到的原始错误是类方法的装饰器,不知何故我弄乱了实例方法的调用站点。让我改一下内容。

标签: python decorator


【解决方案1】:

只需翻转顺序。将@classmethod@staticmethod 放在外面,将装饰器(使用@wraps,因此需要一个裸函数)放在里面。

@classmethod
@plus_decorator
def return_i_class(cls, i):
    return i

【讨论】:

    【解决方案2】:

    尝试倒车。

    当@staticmethod 和@classmethod 是最顶级的装饰器时它会起作用,正如here 解释的那样

    因为您的装饰器需要一个函数,但其​​他两个装饰器都返回描述符对象。

    【讨论】:

      猜你喜欢
      • 2011-09-18
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      • 2018-07-14
      • 2016-05-19
      • 2010-10-16
      相关资源
      最近更新 更多