[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Another dumb scope question for a closure.

Fredrik Lundh

1/9/2008 7:01:00 PM

Steven W. Orr wrote:

> So sorry because I know I'm doing something wrong.
>
> 574 > cat c2.py
> #! /usr/local/bin/python2.4
>
> def inc(jj):
> def dummy():
> jj = jj + 1
> return jj
> return dummy
>
> h = inc(33)
> print 'h() = ', h()
> 575 > c2.py
> h() =
> Traceback (most recent call last):
> File "./c2.py", line 10, in ?
> print 'h() = ', h()
> File "./c2.py", line 5, in dummy
> jj = jj + 1
> UnboundLocalError: local variable 'jj' referenced before assignment

http://docs.python.org/ref/n... has the answer:

"If a name binding operation occurs anywhere within a code block,
all uses of the name within the block are treated as references
to the current block."

> I could have sworn I was allowed to do this. How do I fix it?

use a class to hold state, like everyone else does?

</F>