【问题标题】:What's the difference between the two code snippets below. To me, they look almost identical, but they behave completely different下面的两个代码片段有什么区别。对我来说,它们看起来几乎相同,但它们的行为完全不同
【发布时间】:2019-10-09 11:31:42
【问题描述】:

我有两个看起来几乎相同的代码 sn-ps。但是,当我运行它们时,第一个代码 sn-p 可以完美运行。当我运行第二个脚本时,出现错误: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()

如果我删除第二个 sn-p 中的括号,一切正常,但为什么呢?

【问题讨论】:

  • 在第一个sn-p中,你的装饰器cough_dec返回一个函数return func_wrapper,在第二个sn-p中你的装饰器c_dec返回函数return func_wrapper()的输出,它是None

标签: python python-3.x


【解决方案1】:

您的wrapper_func() 函数不返回任何内容。因此,当您尝试返回wrapper_func() 的结果时,会出现错误。在您的第一个代码 sn-p 中,您返回的是函数 object 而不是函数的结果。

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

【讨论】:

    【解决方案2】:

    引用函数对象和调用该函数之间有很大的区别。括号引发函数调用。如果函数中没有返回语句,则函数返回None

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

    【讨论】:

      猜你喜欢
      • 2023-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 2019-09-08
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多