Help with generators outside of loops.
Steven Bethard
steven.bethard at gmail.com
Wed Dec 8 12:04:38 EST 2004
Christopher J. Bottaro wrote:
> Wow, good advice. One question, how is the generator class implemented so
> that if assigned to a tuple/list, it knows what to do? Is it possible to
> overload the assignment operator kinda like in C++?
Tuple unpacking works with generators because generators implement the
iterator protocol. Any object that implements the iterator protocol can
be used in tuple unpacking:
>>> class I(object):
... def __init__(self, n):
... self.n = n
... self.i = -1
... def next(self):
... self.i += 1
... if self.i == self.n:
... raise StopIteration
... return self.i
... def __iter__(self):
... return self
...
>>> x, y, z = I(3)
>>> x, y, z
(0, 1, 2)
So you're not really overloading the assignment operator; you're taking
advantage of something the assignment operator already does.
Steve
More information about the Python-list
mailing list