Jan-01-2021, 02:47 AM
Hi and Happy New Year!
I am studying Reuven Lerner's book Python Workout, now at chapter 10, Iterators and Generators.
I don't know about classes, I never wrote any, except the examples in this book.
First, I have this, class:
The helper class should do the indexing, such that this code below will print 2 times. (using MyEnumerate, it only prints 1 time, because the index is already at max):
Reuven Lerner says, I should put:
I have tried various things, but my lack of understanding of classes prevents me from getting a working solution.
Can anyone please point me in the right direction??
I think it just needs a small change in MyEnumerate(), but I am not getting there!
I am studying Reuven Lerner's book Python Workout, now at chapter 10, Iterators and Generators.
I don't know about classes, I never wrote any, except the examples in this book.
First, I have this, class:
class MyEnumerate(): # Initializes MyEnumerate with an iterable argument, “data” def __init__(self, data): # Stores “data” on the object as self.data self.data = data # Initializes self.index with 0 self.index = 0 def __iter__(self): # Because our object will be its own iterator, returns self return self def __next__(self): if self.index >= len(self.data): # Are we at the end of the data? If so, then raises StopIteration raise StopIteration # Sets the value to be a tuple, with the index and value value = (self.index, self.data[self.index]) # increment the index in the function above self.index += 1 # return the value tuple return valueThen this code works fine:
for index, letter in MyEnumerate('abc'): print(f'{index} : {letter}')Now, the exercise is make a new class, let's call it MyEnumerate2() and a helper class, MyEnumerateIterator().
The helper class should do the indexing, such that this code below will print 2 times. (using MyEnumerate, it only prints 1 time, because the index is already at max):
e = MyEnumerate2('abc') print('** A **') for index, one_item in e: print(f'{index}: {one_item}') print('** B **') for index, one_item in e: print(f'{index}: {one_item}')
Quote:Rewrite MyEnumerate such that it uses a helper class ( MyEnumerateIterator ), as described in the “Discussion” section. In the end, MyEnumerate will have the __iter__ method that returns a new instance of MyEnumerateIterator , and the helper class will implement __next__ . It should work the same way, but will also produce results if we iterate over it twice in a row.
Reuven Lerner says, I should put:
def __iter__(self): return MyEnumerateIterator(self.data)in MyEnumerate2()
I have tried various things, but my lack of understanding of classes prevents me from getting a working solution.
Can anyone please point me in the right direction??
I think it just needs a small change in MyEnumerate(), but I am not getting there!