问题描述
下面的代码会打印什么? (10或15)
def testClosure(maxIndex):
def closureTest():
返回maxIndex
maxIndex + = 5
return closureTest()
print testClosure(10)
我的问题是闭包函数何时获得maxindex的值?运行
时间或编译时间?
谢谢。
What will the following piece of code print? (10 or 15)
def testClosure(maxIndex) :
def closureTest():
return maxIndex
maxIndex += 5
return closureTest()
print testClosure(10)
My question is when the closure function gets value for maxindex? Run
time or compile time?
Thanks.
推荐答案
我不太明白你想要告诉我们的内容,但如果你认为你的示例代码中有
:
def testClosure(maxIndex):
def closureTest():
返回maxIndex
maxIndex + = 5
返回closureTest()
打印testClosure (10)
你返回一个可调用的函数你错了。这可以很容易看到:
I don''t quite get what you are trying to tell us but if you think that
in your example code:
def testClosure(maxIndex) :
def closureTest():
return maxIndex
maxIndex += 5
return closureTest()
print testClosure(10)
you are returning a callable function you are all wrong. This can be
easily seen by:
15
< type''int''> ;
错误的是你不应该返回closureTest()而是closeTest
。正确的方法是:
15
<type ''int''>
The mistake is that you shouldn''t return closureTest() but closureTest
instead. The correct way would be:
def closureTest():
返回maxIndex
maxIndex + = 5
返回closureTest
def closureTest():
return maxIndex
maxIndex += 5
return closureTest
< function closureTest at 0x00D82530>
<function closureTest at 0x00D82530>
< type''function''>
<type ''function''>
15
干杯,
Jussi
15
Cheers,
Jussi
这篇关于当Closure获得外部变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!