Decorator error: NoneType object is not callable

≡放荡痞女 提交于 2019-12-01 12:42:00
Martijn Pieters

You should return the wrapper function itself, not its result:

def tsfunc(func):
    def wrappedFunc():
        print '%s() called' % func.__name__
        return func()
    return wrappedFunc   # Do not call the function, return a reference instead

Decorators replace the decorated item with the return value of the decorator:

@tsfunc
def foo():
    # ....

is equivalent to:

def foo():
    # ....
foo = tsfunc(foo)

which expands to (in your code):

foo = wrappedFunc()

so you were replacing the function foo with the result of the wrappedFunc() call, not with wrappedFunc itself.

NPE

You need to remove the parentheses in

return wrappedFunc

The decorator is supposed to return the wrapper function, not call it.

With this fix, the code produces:

foo() called
foo() called
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!