When Closure get external variable's value?

Jussi Salmela tiedon_jano at hotmail.com
Mon Dec 18 16:48:33 EST 2006


Huayang Xia kirjoitti:
> It will print 15. The closure gets the value at run time.
> 
> Could we treat closure as part of the external function and it shares
> the local variable with its holder function?
> 

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:

 >>> type(testClosure(10))
15
<type 'int'>

The mistake is that you shouldn't return closureTest() but closureTest 
instead. The correct way would be:

 >>> def testClosure2(maxIndex):
	def closureTest():
		return maxIndex
	maxIndex += 5
	return closureTest

 >>> f2 = testClosure2(10)
<function closureTest at 0x00D82530>
 >>> type(f2)
<type 'function'>
 >>> print f2()
15

Cheers,
Jussi



More information about the Python-list mailing list