Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.python
Re: Another dumb scope question for a closure.
Ben Fisher
1/9/2008 8:47:00 PM
One way to get this to work is:
def inc(jj):
def dummy(jj = jj):
jj = jj + 1
return jj
return dummy
h = inc(33)
print h()
It's not very pretty though, especially when you have many variables
you want to have in the inner scope.
-Ben
On 1/9/08, Mike Meyer <mwm@mired.org> wrote:
> On Wed, 9 Jan 2008 13:47:30 -0500 (EST) "Steven W. Orr" <steveo@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?
>
> Nope. This is one of the things that makes lisper's complain that
> Python doesn't have "real closures": you can't rebind names outside
> your own scope (except via global, which won't work here).
>
> Using a class is the canonical way to hold state. However, any of the
> standard hacks for working around binding issues work. For instance:
>
> >>> def inc(jj):
> ... def dummy():
> ... box[0] = box[0] + 1
> ... return box[0]
> ... box = [jj]
> ... return dummy
> ...
> >>> h = inc(33)
> >>> h()
> 34
>
> <mike
>
> --
> Mike Meyer <mwm@mired.org>
http://www.mired.org/consu...
> Independent Network/Unix/Perforce consultant, email for more information.
> --
>
http://mail.python.org/mailman/listinfo/p...
>
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Re: Another dumb scope question for a closure.
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password