accessing a functions var from a subfunction.
Sebastian Wilhelmi
seppi at seppi.de
Tue Apr 15 04:02:59 EDT 2003
Hi Alex,
Alex Martelli <aleax at aleax.it> wrote:
> Sebastian Wilhelmi wrote:
>
> > Hi,
> >
> > I would like to do the following:
> >
> > -------8<-------8<-------8<-------8<-------
> > def test ():
> > count = 0
> > def inc_count ():
> > count += 1
> > inc_count ()
> > inc_count ()
> > print count
> >
> > test ()
> > -------8<-------8<-------8<-------8<-------
> >
> > This doesn't work (and I even understand, why ;-)
>
> Depends on your tastes in syntax, e.g.:
>
> def test():
> class Bunch: pass
> loc = Bunch()
> loc.count = 0
> def inc_count():
> loc.count += 1
> inc_count()
> inc_count()
> print loc.count
Not my taste ;-)
> def test():
> test.count = 0
> def inc_count():
> test.count += 1
> inc_count()
> inc_count()
> print test.count
Ah, thats great. I tested this, but without the first 'test.'
qualifier, so it didn't work, but this solution is exactly, what I am
looking for.
> Class Bunch (or some highly refined version thereof) IS typically
> around whenever I program, see for example:
>
> http://mail.python.org/pipermail/python-list/2002-July/112007.html
>
> for a typical presentation. Having available the MetaBunch there
> described, I'd start the function as follows:
>
> def test():
> class Bunch(MetaBunch): count=0
> loc = MetaBunch()
> def inc_count():
> loc.count += 1
Nice construct. Thanks for your help.
Bye,
Sebastian
More information about the Python-list
mailing list