1

I am learning enclosing functions, and have the following code:

def parent(x="Hello"):
    text = x

    def son():
        print(text)

    return son

print(parent())

Why does print(parent()) does not print "Hello", but rather prints <function parent.<locals>.son at 0x00000136A32E9EA0>?

I noticed that if I do the following, it will print "Hello":

def parent(x="Hello"):
    text = x

    def son():
        print(text)

    return son

akin = parent()
akin()

What would be the difference between one and another?

6
  • Because you returned son as a reference to the function instead of son(). Commented Mar 20, 2019 at 4:08
  • Why does it print "hello" in the second example? Commented Mar 20, 2019 at 4:11
  • 1
    Because you call son by appending () to akin. Commented Mar 20, 2019 at 4:13
  • I guess what I can't understand is what the difference is between calling parent() directly, and doing it through a reference to it (akin variable). Why in the second example son() is called. If I print akin variable, I get the same function as printing parent: <function parent.<locals>.son at 0x00000136A3E57E18> (only within a different memory location) Commented Mar 20, 2019 at 4:17
  • 1
    What's the difference? In your first sample you are printing out a reference to the function son. In your 2nd sample you are assigning akin to the reference of the function son. Both are references and needs to be executed if you want it to print ("text") Commented Mar 20, 2019 at 4:26

2 Answers 2

2

Function parent returns another function. That function must be called to take effect:

print(parent()())

Or, to emphasize the calling sequence:

print((parent())()
Sign up to request clarification or add additional context in comments.

Comments

0

Here you need to return son()

def parent(x="Hello"):
    text = x

    def son():
        print(text)

    return son # return son()

print(parent())

Here you get difference result ,because are referring akin()

def parent(x="Hello"):
    text = x

    def son():
        print(text)

    return son

akin = parent()
akin() # print(akin) will get the same output of first program

Difference is every function a have memory address, you referring a function without parenthesises () will return address of the function . So in your first program your returning the memory address of the function so you can access the content using parent()() or return the actual value from the function instead of returning address

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.