You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python装饰器实现报错:‘NoneType’对象不可调用,求问题排查

问题分析与解决

你的错误原因很明确——装饰器返回了函数调用的结果,而非函数本身。

看你的maint装饰器最后一行:return greet(),这里你直接调用了greet函数,而greet没有返回任何值(Python中无显式return的函数默认返回None)。当你用@maint语法装饰hello时,Python会自动执行hello = maint(hello),这时候hello就被赋值成了None。后续再调用hello(),自然就会抛出'NoneType' object is not callable的错误。

修正后的代码

只需要把返回语句改成返回函数对象即可:

def maint(item1):
    def greet():
        print("Good Morning")
        item1()
        print("Tanish")
    return greet  # 去掉括号,返回函数本身而非调用结果

# decorator----
@maint
def hello():
    print("Hello")

hello()

运行结果

执行这段修正后的代码,你会得到预期的输出:

Good Morning
Hello
Tanish

简单梳理下装饰器的核心逻辑:装饰器本质是一个接收函数作为参数,并且返回新函数的工具函数。返回的新函数会替代原来的被装饰函数,这样当你调用原来的函数名时,实际执行的是装饰器返回的新函数。

内容的提问来源于stack exchange,提问作者Tanish Sarmah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 20:48:14