【问题标题】:Why not use parenthesis on return functions inside functions in Python?为什么不在 Python 函数内的返回函数上使用括号?
【发布时间】:2015-06-02 11:23:40
【问题描述】:

我正在阅读 this tutorial,在 Returning Functions 部分下,有一个类似下面的示例:

def parent(n):

    def child1():
        return "Printing from the child1() function."

    def child2():
        return "Printing from the child2() function."

    if n == 10: return child1
    else: return child2

作者提到返回函数中不应该有括号,但没有给出任何详细解释。我相信这是因为如果添加了括号,那么该函数将被调用,并且以某种方式将丢失流。但我需要一些更好的解释才能更好地理解。

【问题讨论】:

  • I believe that it is beacause if parenthisis are added, then the function will get called - 你是对的
  • 是的,我认为它是这样工作的,但我相信更好的解释对每个人都有好处,尤其是初学者。

标签: python python-decorators


【解决方案1】:

如果您在返回函数中添加括号,即(),那么您将返回该函数的返回值(即该函数被执行并返回其结果)。否则,您将返回对该可重复使用的函数的引用。也就是说,

f = parent(1)
f()  # executes child2()

【讨论】:

  • 投票前更正语法:)
【解决方案2】:
return func()  # returns the result of calling func
return func    # returns func itself, which can be called later

【讨论】:

    【解决方案3】:

    我们正在定义函数 child1()child2() 并在嵌套范围(此处为父级)之外返回对这些函数的引用。因此,每次调用 parent 函数时,都会有 child1child2 的新实例。

    我们只需要这些引用。这就是没有括号的原因。如果您添加括号,则该函数将被调用。

    【讨论】:

      猜你喜欢
      • 2019-06-18
      • 2013-10-05
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      相关资源
      最近更新 更多