Below is an iterator that given a start and a stop values it yields integers incrementing by one:
class Iterator:
def __init__(self, start, stop):
self.start = start
self.stop = stop
self._start = self.start
def __iter__(self):
return self
def __next__(self):
self.current = self._start
if self.current >= self.stop:
raise StopIteration
self._start += 1
return self.current
I see the above version used by everyone. Woudln't the following version be more readable? It also avoids the use of the if conditional if that's a good thing.
def __next__(self):
self.current = self._start
while self.current < self.stop:
self._start += 1
return self.current
raise StopIteration
Aucun commentaire:
Enregistrer un commentaire