为什么下面的代码给出错误“error:'NoneType'对象不可调用”?

2024-09-22 16:29:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python实现decorators,但在第14行出现了一个错误,即hello()

    #The code-
    def maint(item1):
        def greet():
            print("Good Morning") 
            item1()
            print("Tanish")
        return greet()

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

我做错了什么


Tags: thedecoratorshelloreturndef错误codegood
1条回答
网友
1楼 · 发布于 2024-09-22 16:29:07
return greet()

在decorator中,调用greet()返回其结果。由于greet()没有显式返回,因此结果是None。这将有助于认识到decorator是以下内容的简写语法:

def hello():
   pass

hello = maint(hello)

注意hello是如何被重新分配给maint()返回的任何内容的。在您的情况下,hello被重新分配给None。因此调用hello()会导致错误

要解决这个问题,只需return greet不带括号。装饰器总是返回一个函数。他们不应该调用该函数

相关问题 更多 >