我写了一个这样的函数装饰器:
def tsfunc(func):
def wrappedFunc():
print '%s() called' % func.__name__
return func()
return wrappedFunc()
@tsfunc
def foo():
pass
foo() # to get it work, use foo instead of foo()
foo()
我收到以下错误消息:
foo() called
Traceback (most recent call last):
File "decorator.py", line 11, in <module>
foo()
TypeError: 'NoneType' object is not callable
我通过将“foo()”替换为“foo”来让它工作。但我仍然没有得到我预期的结果:
foo() called
似乎 foo 函数只被调用了一次。
请帮助我理解为什么会这样。
请您参考如下方法:
你应该返回包装函数本身,而不是它的结果:
def tsfunc(func):
def wrappedFunc():
print '%s() called' % func.__name__
return func()
return wrappedFunc # Do not call the function, return a reference instead
装饰器用装饰器的返回值替换被装饰的项目:
@tsfunc
def foo():
# ....
相当于:
def foo():
# ....
foo = tsfunc(foo)
扩展为(在您的代码中):
foo = wrappedFunc()
因此您将函数 foo 替换为 wrappedFunc() 调用的结果,而不是 wrappedFunc 本身。
