Reputation: 1883
Suppose we have this class definition:
class Series(object):
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
In my opinion, this implementation is logically wrong. Indeed, we cannot have two independant iterators of this class:
s = Series(1,10)
it1 = iter(s)
print(next(it1)) # prints 1
it2 = iter(s)
print(next(it2)) # should print 1 but it prints 2
So my question is: Is it necessary to define another class for series_iterator
in order to implement it well, or there is a way to implement a iterable and its iterator as the same class?
Upvotes: 2
Views: 486
Reputation: 27283
So my question is: Is it necessary to define another class for
series_iterator
in order to implement it well?
No:
class Series:
def __init__(self, low, high):
self.low = low
self.high = high
def __iter__(self):
current = self.low
while current <= self.high:
current += 1
yield current - 1
By making __iter__
a generator, you don't have to define a new class for proper iterable behaviour. This won't always solve everything, since it's not as powerful as a seperate class, but in a large amount of cases, it's more than enough — and clearer.
Note that you don't have to implement __next__
now — that is already defined for you on the generator type.
Upvotes: 4