When Closure get external variable's value?

Huayang Xia huayang.xia at gmail.com
Tue Dec 19 11:15:51 EST 2006


That is a really concise and precise answer. Thanks.

So the object binding can only happen explicitly at the closure
declaration argument list(non-free variable).

On Dec 19, 10:37 am, Fredrik Lundh <fred... at pythonware.com> wrote:
> Huayang Xia wrote:
> > When does the closure get the value of the maxIndex in the following
> > code snippet?
>
> >          def testClosure(maxIndex) :
>
> >              def closureTest():
> >                  return maxIndex
>
> >              maxIndex += 5
>
> >              return closureTest()
>
> >          print testClosure(10)
>
> > I thought it should be 10 instead of 15. That was wrong.free variables in an inner scope bind to variables in the outer scope,
> not objects.
>
> if you want to bind to objects, use explicit binding:
>
>      def closureTest(maxIndex=maxIndex):
>          return maxIndex
> 
> </F>




More information about the Python-list mailing list