【问题标题】:How to use decorators on methods? [closed]如何在方法上使用装饰器? [关闭]
【发布时间】:2018-01-20 20:03:53
【问题描述】:

如何在方法上使用装饰器,把它放在类之外只会返回一个内存地址:<function decor at 0x104e167b8>,把它放在里面会引发一个

TypeError: 'NoneType' object is not callabl

我也尝试添加*args,因为方法的参数中有self

【问题讨论】:

  • 您能否发布您的代码以便我们更好地理解您的问题?
  • 你能提供一些代码示例来解决这些错误吗?
  • 看看Documentation 可能会有所帮助

标签: python methods decorator


【解决方案1】:

类中装饰器的示例实现如下所示:

class Foo:
    def __init__(self):
        pass

    def decor(function):
        def wrap(*args, **kwargs):
            # Whatever your decorator does here
            return function(*args, **kwargs)
        return wrap

    @decor
    @staticmethod
    def bar():
        pass

或者在 Foo 的实例上调用它:

foo = Foo()
foo.bar()

如果你的装饰器需要访问self:

class Foo:
    def __init__(self, spam):
        if spam is not None:
            self.spam = spam

    def require_spam(function):
        def wrap(self, *args, **kwargs):
            try:
                self.spam
            except AttributeError:
                return
            return function(self, *args, **kwargs)
        return wrap

    @require_spam
    def bar(self):
        pass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多