PyotrVanNostrand
PyotrVanNostrand

Reputation: 248

Function assigned to a variable?

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)
z()

return value of f() is assigned to variable z when this happens it invokes function f() I understand so far but how does z() directly returns the value returned by f ? Could you explain this briefly ?

Upvotes: 1

Views: 62

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51683

You assign the returnvalue of the call of f() to z. You do not assign f to z.

So calling z() will only execute the returned inner g function - not the whole f.

On z = f() you get the printout of f and then g as function returned. On consecutive calls to z() you execute the inner g function directly.

Upvotes: 2

maxbear123
maxbear123

Reputation: 202

You have effectively created a pointer (in variable z) to the function f(x). Calling z() therefore calls f(x). Because f(x) returns g, z() will also return g, as calling z() executes f(x).

Upvotes: 1

Related Questions