Why not use parentheses for return functions inside functions in Python?

I am reading this tutorial and there is an example in the Returned Functions section , for example:

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 returned functions should not have parentheses in them, but without a detailed explanation. I believe this is because if the parentheses are added then the function will be called and somehow the thread will be lost. But I need a better explanation to get a good understanding.

+3


source to share


3 answers


If you add ie parentheses to the return function ()

, then you will return the return value of this function (i.e. the function will be executed and its result will be returned). Otherwise, you return a reference to that function that you can reuse. I.e



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

      

+6


source


return func()  # returns the result of calling func
return func    # returns func itself, which can be called later

      



+3


source


We define functions child1()

and child2()

and return references to those functions outside of the nested scope (here, parent). This way, every time you call the function parent

, new instances of child1

and appear child2

.

And we only want these links. Therefore, there are no parentheses. If you add parentheses, the function will be called.

0


source







All Articles