amuys at shortech.com.au
Thu Feb 28 00:47:49 CET 2002
"Emile van Sebille" <emile at fenx.com> wrote in message news:<a5jbra$7ok00$1 at ID-11957.news.dfncis.de>...
> "Michael P. Soulier" <msoulier at nortelnetworks.com_.nospam> wrote in
> message news:slrna7q9m0.4pb.msoulier at pmerd071.ca.nortel.com...
> > Hello.
> > While I know about bound methods in Python, I'm wondering if a
> > closure can be implemented. Can it?
> > Example: I want to pass an arbitrary code reference into a closure
> > have all of its variables preserved.
> > ie.
> > print "the current count is %d" % counter; counter += 1
> > Can I pass the above code into a closure, and then simply call it
> > repeatedly and see counter increment itself? If I pass in a function
> with a
> > local variable, that local will be reset each time, and I don't want
> to use a
> > global.
> I don't understand closures, but I might try something like:
> class Counter:
> def __init__(self):
> self.count = 0
> def __int__(self):
> self.count += 1
> return self.count
> counter = Counter()
> print "the current count is %d" % counter
That works, as does using a generator:
counter = 0
print "the current count is %d % counter
counter += 1
yield counter - 1 # might as well return it :)
counter = Counter()
- the current counter is 0
- the current counter is 1
More information about the Python-list