0
def f(x):
    def g():
        x='abc'
        print('x=',x)
    def h():
        z=x
        print('z=',z)
    x=x+1
    print('x=',x)
    h()
    g()
    print('x=',x)
    return g
x=3
z=f(x)
print('x=',x)
print('z=',z)
z()

Output

x= 4
z= 4
x= abc
x= 4
x= 3
z= <function f.<locals>.g at 0x000000F6919EF9D8>
x= abc

I don't understand how we call z() as a function when it is a variable. Also, I don't understand how we got the last 2 lines of output.

5
  • 1
    f(x) returns g which is a function, hence calling z() will call g(). Commented Aug 11, 2019 at 6:21
  • @Austin but z=f(x), so why does calling z() not execute the print statements in f()? Commented Aug 11, 2019 at 6:34
  • why should it execute prints inside f()? Commented Aug 11, 2019 at 6:39
  • @Austin the statement z=f(x) executes all the print statements within f, then why is z() different? Commented Aug 11, 2019 at 6:42
  • 2
    please read the answer posted below. z is holding only the returned value from function f(x). That returned value happened to be a function. So calling z() calls that function and that function includes only one print statement. Commented Aug 11, 2019 at 6:44

1 Answer 1

7

in python all objects are first class objects. you can assign names (variables) to any object; that includes functions.

the relevant parts of your first question are:

def f(x):
    def g():
        x='abc'
    return g

i.e. f returns a function. you can assign and call it with:

z = f(3)
print(z)  # <function f.<locals>.g at 0x000000F6919EF9D8>
z()

for your second question: print(z) (see in the code above) will generate a line of output and calling z() (i.e. g()) will print x= abc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.