如何解决返回wrapper函数时出现'NoneType' object is not callable报错
错误产生原因
错误的核心是装饰器返回值类型错误:你在new_decorator的最后一行写的是return wrapper_funct(),加括号会直接执行wrapper_funct函数,而wrapper_funct没有显式定义返回值,Python会默认给它返回None。后续你把返回的None赋值给了func_needs_decorator变量,再尝试调用func_needs_decorator()的时候,本质是在调用None,自然就会触发'NoneType' object is not callable报错。
原代码完整运行流程
- 第一步:先完成两个函数的定义,分别是
func_needs_decorator和new_decorator,此时不会执行函数内部的逻辑 - 第二步:执行
func_needs_decorator = new_decorator(func_needs_decorator),把原func_needs_decorator函数作为参数传入new_decorator - 第三步:
new_decorator内部定义好wrapper_funct后,遇到return wrapper_funct()语句,直接触发wrapper_funct的执行:- 打印
Some extra code before the original function - 调用传入的原函数
original_funct,打印I wanna a decorator urgently - 打印
Some extra code after the original funciton wrapper_funct无返回值,默认返回None
- 打印
- 第四步:
new_decorator执行完成,把返回的None赋值给变量func_needs_decorator,此时func_needs_decorator已经是None类型,不再是可调用的函数 - 第五步:执行
print(func_needs_decorator()),尝试调用None,直接触发类型错误
修复方案
只需要修改new_decorator的返回语句,去掉wrapper_funct后面的括号,返回函数本身而不是函数的执行结果即可:
def func_needs_decorator(): print("I wanna a decorator urgently") def new_decorator(original_funct): def wrapper_funct(): print("Some extra code before the original function") original_funct() print("Some extra code after the original funciton") # 去掉括号,返回函数本身 return wrapper_funct func_needs_decorator = new_decorator(func_needs_decorator) print(func_needs_decorator())
内容的提问来源于stack exchange,提问作者Berke Balcı
相关产品推荐
相关产品推荐

