在这段代码中:
results = []
for i in [1, 2, 3, 4]:
def inner(y):
return i
results.append(inner)
for i in results:
print i(None)
Run Code Online (Sandbox Code Playgroud)
输出是"函数内部在0x107dea668"
如果我改变我到其他盘符,例如:
results = []
for i in [1, 2, 3, 4]:
def inner(y):
return i
results.append(inner)
for j in results:
print j(None)
Run Code Online (Sandbox Code Playgroud)
输出为"4"
回答
results = []
for i in [1, 2, 3, 4]:
def inner(y):
print "in inner:%s " % id(i)
return i
results.append(inner)
# i -> 4
for i in results:
# i -> func inner
print "i: %s" % i
print "in loop: %s " % id(i)
# func inner <===> A
# i == A -> return i -> return A, so when call funtion inner, will return itself
# print "call: %s" % i(None)
print "call: %s" % i(None)(None)(None)
print "------------------------------"
Run Code Online (Sandbox Code Playgroud)
i:函数内部在0x101344d70
在循环中:4315172208
在内部:4315172208
在内部:4315172208
在内部:4315172208
调用:函数内部在0x101344d70
i:函数内部在0x101344de8
在循环中:4315172328
在内部:4315172328
在内部:4315172328
在内部:4315172328
调用:函数内部在0x101344de8
i:函数内部在0x101344e60
在循环中:4315172448
在内部:4315172448
在内部:4315172448
在内部:4315172448
调用:函数内部在0x101344e60
I:在0x101344ed8起作用内
4315172568:在回路
中内:4315172568
中内:4315172568
中内:4315172568
呼叫:函数内在0x101344ed8