我正在阅读本教程,并在返回函数部分下面有一个例子,如下所示:
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 child2The 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()更多推荐
发布评论