有点晚了,但希望这会有所帮助,扩展为什么提供的答案被接受
如错误所述,“NoneType”表示我们尝试调用的实例/对象没有类型(它不是函数/int/boolean/class/instance)。它的类型只是“无”所以总而言之,装饰器只不过是对闭包的扩展使用,其函数被视为一等公民(您可以获得关于闭包的详细视图
这基本上意味着装饰器希望返回一个函数,比如说大多数情况下的包装器,原始函数保持不变并使用装饰器调用
def tsfunc(func):
def wrappedFunc():
print '%s() called' % func.__name__
return func()
return wrappedFunc() -> Here the function is not returned but called eventually
@tsfunc
def foo():
pass
foo() - > calling this again doesnt make sense to trigger the decorator, since a reference for the method foo is enough. Hence foo works fine but foo() doesn't (method call has completed already but no value is returned) If you try like this, you would see that the variable has 'None' type
def tsfunc(func):
def wrappedFunc():
print '%s() called' % func.__name__
return func()
return wrappedFunc -- Here I made the correction
@tsfunc
def foo():
pass
var1 = foo()
print(var1)
This what happened with the call to foo() when you had the incorrect way of calling the wrapper function rather than returning just the function
So for a decorator to function as per the norms, it should return a wrapper function with the original function being unaltered. And hence it should be rewritten as per the accepted answer