full closures

Martin v. Loewis martin at v.loewis.de
Wed Feb 27 15:55:39 EST 2002


"Emile van Sebille" <emile at fenx.com> writes:

> 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
> 
> Hopefully, someone will post something pythonish illustrating closures.
> Maybe this time I'll get it.  ;-)

As Zenin points out, Python uses objects to emulate closures, whereas
Lisp uses closures to emulate objects. So your solution is very
Pythonic.  To allow calling the object over and over again, you could
implement __call__ instead of __init__.

With Python 2.2, the yield statement allows that kind of data flow as
well.

Regards,
Martin



More information about the Python-list mailing list