Dec-16-2020, 05:13 AM
(This post was last modified: Dec-16-2020, 05:13 AM by deanhystad.)
The function foo returns the function bar, it does not call the function. You then use that return value to call function bar(). So when you called g(20) you were actually calling foo.bar(20).
The more interesting thing in this example is where does bar get a value for x? Why is x hanging around after foo is done executing? What is keeping garbage collection from throwing x away? Ponder that for a bit.
And if you are under the impression that each Python function has some static namespace where it keeps all this info, look at this example:
The more interesting thing in this example is where does bar get a value for x? Why is x hanging around after foo is done executing? What is keeping garbage collection from throwing x away? Ponder that for a bit.
And if you are under the impression that each Python function has some static namespace where it keeps all this info, look at this example:
def foo(x): def bar(y): return x*y return bar a = foo(10) b = foo(20) print(a(2), b(2))
Output:20, 40
a is the function bar() with a context for bar() that remembers x == 10. b is also the function bar() with a context that remembers x == 20. Interesting.