lexical closures and python
Ignacio Vazquez-Abrams
ignacio at openservices.net
Thu Sep 6 05:03:06 EDT 2001
On Thu, 6 Sep 2001, John Beppu wrote:
> Notice how grande and pequeno remember the value of current, but
> also notice that they each remember their own current variable.
> Because current is lexically bound to a new closure each time
> sequence_iterator() is invoked, grande and pequeno do not
> interfere with each other.
>
> Interesting, no?
Yes. The Pythonic equivalent (as I know it) would be:
class sequence_iterator:
a=None
def __init__(self, a):
self.a=a
def __call__(self):
b, self.a=self.a, self.a+1
return b
grande=sequence_iterator(235123)
pequeno=sequence_iterator(1)
for i in range(5):
print grande()
print pequeno()
--
Ignacio Vazquez-Abrams <ignacio at openservices.net>
More information about the Python-list
mailing list