0

I totally understand the idea of different scopes in Python but I can't understand this code clearly so I'd be pleased if someone can explain it to me, the return in line 18 what does it mean? shouldn't it be return g() for example? what does g means here is it a variable ? the output is z=function g at 0x15b43b0 , what does this mean?

one last thing , what does z() in the last line measn? there is no function called z !!

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()
1
  • 1
    The function f returns the value of g, which is a function, so f returns a function. In the main code, that function is stored in z, so z really is a function, and can be called. Commented Jan 24, 2018 at 20:28

2 Answers 2

3

the return in line 18 what does it mean?

It's returning the function object g itself.

shouldn't it be return g() for example?

Not necessarily. It's perfectly acceptable to pass around functions as they're just objects like anything else in Python. Both return g and return g() are valid, and mean different things.

what does g means here is it a variable?

g is the name bound to a function object, which when called prints x=abc and then returns None. Yes, g is a variable (it's a local variable).

the output is z=function g at 0x15b43b0 , what does this mean?

It means the name z is bound to a function named g at memory location 0x15b43b0. (Hint: It's actually the same function object that was bound to the name g in the inner scope)

one last thing , what does z() in the last line measn?

It means call the object that the name z is bound to. i.e. it calls the function that was returned by f.

there is no function called z

There is no function with the __name__ attribute equal to z here. But the name z can still be bound to a function object. Remember that objects can have more than one name (or no names at all).

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

Comments

1

g is the name of a function defined with a def. g() invokes the function and gives you the result, while g is a name (a reference that is) for the function object itself.

Yes there is a funtion named 'z'. It is equal to the function returned by the invocation of f(x), that is function f invoked with arg x. This is the function g as per the line with return g

Besides scopes you may want to check high-order functions and closure concepts.

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.