'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 ?



Solution 1:[1]

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).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 maxbear123