有人可以告诉我为什么这个python装饰器不起作用吗?

问题描述

def decoratorrt(func):
    def innerht():
        print("hello there")
        func()
        print("it has ended")
        return innerht

@decoratorrt
def hellot():
    print("hello","are you in")

hellot()

我收到的错误消息是TypeError Traceback(最近一次通话最近) 在 ----> 1 hellot()

TypeError:“ nonetype”对象不可调用

解决方法

您缩进了return innerht;应该是decoratorrt的返回值,但是如果没有返回值,decoratorrt会隐式返回None(而innerht会试图返回自身)。固定功能:

def decoratorrt(func):
    def innerht():
        print("hello there")
        func()
        print("it has ended")
    return innerht  # Dedented