为什么不在Python中的函数内使用括号?(Why not use parenthesis on return functions inside functions in Python?)

编程入门 行业动态 更新时间:2024-10-22 20:40:53
为什么不在Python中的函数内使用括号?(Why not use parenthesis on return functions inside functions in Python?)

我正在阅读本教程,并在返回函数部分下面有一个例子,如下所示:

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'm reading this tutorial and under the Returning Functions part, there's an example something like below:

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

The author mentions that the return functions should not have parenthesis in them but without giving any detailed explanation. I believe that it is because if parenthesis are added, then the function will get called and in some way the flow will be lost. But I need some better explanation to get a good understanding.

最满意答案

如果将括号ie ()添加到返回函数中,那么您将返回该函数的返回值(即函数被执行并返回结果)。 否则,您将返回可以重新使用的该函数的引用。 那是,

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

If you add parenthesis i.e. () to the return function then you will be returning the return-value of that function (i.e. the function gets executed and its result is returned). Otherwise, you are returning a reference to that function that can be re-used. That is,

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

更多推荐

本文发布于:2023-07-17 13:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1144975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   函数   Python   functions   return

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!