def f(p, k):
def g():
print(k)
if k == 0:
f(g, 1)
else:
p()
f(None, 0)
我觉得在f(None, 0)
执行后,执行到f(g, 1)
后k
应该是1
,但为什么执行还是0
.
PHP中文网2017-04-18 10:33:01
This should be a closure, we can change this function
def f(k):
def g():
print(k)
return g
a = 1
x = f(a)
a = 2
x()
# 打印出
# 1
Would this make it easier to understand?
You can read this blog, which explains the principle of closure at the bottom level. Detailed explanation of Python closures