下面的两段代码有什么不同。对我来说,他们看起来几乎一模一样,但他们的行为却完全不同

2024-06-16 13:58:21 发布

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

我有两个看起来几乎完全相同的代码片段。但是,当我运行它们时,第一个代码段运行得非常好。当我运行第二个脚本时,得到错误:TypeError: 'NoneType' object is not callable

为什么???你知道吗

我试过重新命名函数。我试过修改函数中的文本。你知道吗

def cough_dec(func):
    def func_wrapper():
        print("*cough*")
        func()
        print("*cough*")

    return func_wrapper


@cough_dec
def question():
    print('can you give me a discount on that?')


@cough_dec
def answer():
    print("it's only 50p, you cheapskate")


question()
answer()

=============================================

def c_dec(func):

    def wrapper_func():
        print('something')
        func()
        print('anything')

    return wrapper_func()


@c_dec
def say_hello():
    print("Hello World!")


@c_dec
def bye():
    print("Goodbye World!")


say_hello()
bye()

如果我去掉第二段中的括号,一切都很好,但为什么呢?你知道吗


Tags: 函数answeryouhelloworldreturndefwrapper
2条回答

wrapper_func()函数不返回任何内容。因此,当您试图返回wrapper_func()的结果时,会出现一个错误。在第一个代码段中,返回的是函数对象而不是函数的结果。你知道吗

看到这个非常相似的问题:Python NoneType object is not callable (beginner)

引用函数对象和调用所述函数之间有很大的区别。括号表示函数调用。如果函数中不存在return语句,则函数返回None。你知道吗

正如人们所料,None是不可调用的,但函数对象是!你知道吗

相关问题 更多 >