I have the following code which I wrote for a course which runs fine:
def reverse_iter(iterable):
"""Return a generator that yields items from iterable in reverse order"""
last = len(iterable) - 1
while last >= 0:
yield iterable[last]
last -= 1
The next part of the assignment is to turn this function into a class. I know this not practical but it is what is being asked. I have very limited knowledge about classes but I came up with the following code:
class ReverseIter:
"""Class whose instances iterate the initial iterable in reverse order"""
def __init__(self, iterable):
self.iterable = iterable
def iterreverse(self):
last = len(self.iterable) - 1
while last >= 0:
yield self.iterable[last]
last -= 1
nums = [1, 2, 3, 4]
it = ReverseIter(nums)
print(iter(it) is it)
print(next(it) == 4)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
The output always reads TypeError: 'ReverseIter' object is not iterable. I hav eno idea why this is coming up. Any explanations or suggestions would be helpful. The output of the print statements above by the way should be True, True, 3, 2, 1, Stop Iteration respectively.