[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.python

Another dumb scope question for a closure.

Steven W. Orr

1/9/2008 6:48:00 PM

2 Answers

Waldemar Osuch

1/9/2008 10:52:00 PM

0

On Jan 9, 11:47 am, "Steven W. Orr" <ste...@syslang.net> 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
>
> I could have sworn I was allowed to do this. How do I fix it?
>

I have seen this approach on ActiveState Cookbook but can not find a
reference to it right now.

>>> def inc(jj):
.... def dummy():
.... dummy.jj += 1
.... return dummy.jj
.... dummy.jj = jj
.... return dummy
....
>>> h = inc(33)
>>> h()
34
>>> h()
35
>>> i = inc(12)
>>> i()
13
>>> i()
14

Waldemar

Waldemar Osuch

1/9/2008 10:59:00 PM

0

On Jan 9, 3:52 pm, Waldemar Osuch <waldemar.os...@gmail.com> wrote:
> On Jan 9, 11:47 am, "Steven W. Orr" <ste...@syslang.net> 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
>
> > I could have sworn I was allowed to do this. How do I fix it?
>


> I have seen this approach on ActiveState Cookbook but can not find a
> reference to it right now.
>
> >>> def inc(jj):
>
> ... def dummy():
> ... dummy.jj += 1
> ... return dummy.jj
> ... dummy.jj = jj
> ... return dummy
> ...>>> h = inc(33)
> >>> h()
> 34
> >>> h()
> 35
> >>> i = inc(12)
> >>> i()
> 13
> >>> i()
>
> 14
>
> Waldemar

Here it is:
http://aspn.activestate.com/ASPN/Cookbook/Python/Rec...