>The easiest way to do this seemed to be to write a class, like so:
>
> class Iterator:
> def __init__(self, list):
> self.list=list
> self.pos=-1
> return self.generator
> def generator(self):
> self.pos = self.pos + 1
> return self.list[self.pos]
I was thinking of the same thing. I would like to solve it in another
way, by introducing the operator __call__ for instances. Example:
class Iterator:
def __init__(self, arg):
# some init stuff;
def __call__(self):
return self.next();
next= Iterator(arg); # note: next is the iterator object!!
i= next();
while (i): f(i); i=next();
next.reset(); # not directly possible with Steven's approach
The feature can also be used for functional programming idioms (remember
the discussion about lambda; I do not want to discuss that further here).
I was tempted to insert the code needed for this functionality into
my Python interpreter (it is easy...). It does not cost any performance
as long as you do not use it.
I think Guido is right: __init__ should not return an arbitrary value.
I might imagine that __init__ returns None or self. If it returns self,
that means construction was ok. If it is None, construction failed. Example:
file = File('myfile');
if ( file ): Process(file);
else: TellUser('open for myfile failed');
Would be nice, but is not needed.
-- Thomas
----------------------------------------------------------
Thomas Kofler |Email: kofler@ubilab.ubs.ch
Union Bank of Switzerland |Tel: +41-1-236 4567
Bahnhofstr. 45 |Fax: +41-1-236 4671
CH-8021 Zurich, Switzerland |
----------------------------------------------------------