0
assigning a variable to a function
Hello something that I do not understand def foo(): def bar(): print(spam) spam = 'ham' bar() spam = 'eggs' bar() return bar b = foo() b() On this configuration, the output will be ham eggs eggs Why b= foo() and b() are not producing the same output ? I encounter this several time and I cannot understand.
3 Respostas
+ 1
First of, you didn't have to assign it to a variable. You could have just did:
foo()
If you did assign it in a variable (like you did), I think it'd produce the last result. This much I know.
The same way:
for x in range(5):
pass
print(x)
Output would be 4 as it was iterated last.
I await a better answer though...😃😃😃
0
def foo():
def bar():
print(spam)
spam = 'ham'
bar()
spam = 'eggs'
bar()
return bar
print("result of foo(): \n")
foo()
print("\nresult of b():\n ")
"""do not use b = foo() with brackets. Instead use it as follows and it yields the same result!"""
b = foo
b()
0
So I found the answer.
When you do : b = foo() you return the function bar and assign it to b.
You have an enclosure with "spam" and its last value is "eggs"
So b() is equivalent to bar(), but you could not write bar() only because it is inside foo() .