为什么我尝试调用此函数时会收到 NoneType object is not callable 的错误消息?

Why do I get an error message of NoneType object is not callable when I try to call this function?

def decorator_function(original_func):
    def wrapper_func():
        print('Run this code before the function that needs docorated')
        original_func()
        print('Run this code after the function that needs decorated has been called')
    return wrapper_func()

def function_needing_decorated():
    print('I need to be decorated')


decorator_test = decorator_function(function_needing_decorated)

我猜这与对 return 的误解有关,因为我很确定我不应该添加括号。我的问题是为什么它不起作用?为什么它是 NoneType 而不是 NoneType 当我不把括号放在那里时。你越详细越好,因为我真的需要了解这一点。

您不应该在装饰器中调用包装器 - 您应该 return 包装器本身。

return wrapper_func

您正在做的是return调用包装器的结果;因为那个包装器本身没有 return 任何装饰器本身现在什么都没有。

在函数名后面加上括号(wrapper_func()),实际上是在调用函数。

Wrapper Function 正在评估,它生成的值由 decorator_function 编辑 return。

wrapper_func() 没有 return 语句,所以它的 return 值是 None,这是不可调用的。

另一方面,

wrapper_func 被视为变量——第一个 class 函数。因此,它是可调用的。