为什么不在 Python 函数内部的 return 函数上使用括号?
Why not use parenthesis on return functions inside functions in Python?
我正在阅读 this tutorial 并且在 返回函数 部分下,有一个如下所示的示例:
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
作者提到return函数中不应该有括号但没有给出任何详细解释。我相信这是因为如果添加括号,那么该函数将被调用并且以某种方式将丢失流程。但是我需要一些更好的解释才能更好地理解。
如果您添加括号,即 ()
到 return 函数,那么您将 returning 该函数的 return 值(即函数被执行其结果是 returned)。否则,您将 return 引用可重复使用的函数。也就是说,
f = parent(1)
f() # executes child2()
return func() # returns the result of calling func
return func # returns func itself, which can be called later
我们正在定义函数 child1()
& child2()
并在嵌套范围(此处为父级)之外返回对这些函数的引用。因此,每次调用 parent
函数时,child1
& child2
.
的新实例
我们需要这些引用 only.That 这就是没有括号的原因。如果您添加括号,那么该函数将被调用。
我正在阅读 this tutorial 并且在 返回函数 部分下,有一个如下所示的示例:
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
作者提到return函数中不应该有括号但没有给出任何详细解释。我相信这是因为如果添加括号,那么该函数将被调用并且以某种方式将丢失流程。但是我需要一些更好的解释才能更好地理解。
如果您添加括号,即 ()
到 return 函数,那么您将 returning 该函数的 return 值(即函数被执行其结果是 returned)。否则,您将 return 引用可重复使用的函数。也就是说,
f = parent(1)
f() # executes child2()
return func() # returns the result of calling func
return func # returns func itself, which can be called later
我们正在定义函数 child1()
& child2()
并在嵌套范围(此处为父级)之外返回对这些函数的引用。因此,每次调用 parent
函数时,child1
& child2
.
我们需要这些引用 only.That 这就是没有括号的原因。如果您添加括号,那么该函数将被调用。