blob: 2b1e14ee0753591d830c2ff841f9f025d3dd21d7 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
# this class implements an iterator
# python needs to be told when to stop iterating, this is done by raising StopIteration exception
class ReverseString():
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.data[self.index]
def main():
foo = ReverseString('foobar')
for c in foo:
print(c)
if __name__ == "__main__":
main()
|