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

Tan*_*mah -1 python python-decorators

我试图在 python 中实现装饰器,但在第 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()
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Cod*_*ice 5

return greet()
Run Code Online (Sandbox Code Playgroud)

在装饰器中,您调用greet()返回其结果。由于greet()没有显式返回,结果是None。认识到装饰器是以下内容的速记语法会有所帮助:

def hello():
   pass

hello = maint(hello)
Run Code Online (Sandbox Code Playgroud)

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

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