diff options
author | Kyle K <kylek389@gmail.com> | 2017-04-01 03:34:41 -0500 |
---|---|---|
committer | Kyle K <kylek389@gmail.com> | 2017-04-01 03:34:41 -0500 |
commit | a3d3368d9f024052632dc87b5d52e26a223c7869 (patch) | |
tree | 14f542224ba986030ea2a9424480a3975e4e72bb /iterator.py | |
parent | 007a3ca9ea7c23f14341da104de47ecc919dfa77 (diff) | |
download | PythonPractice-a3d3368d9f024052632dc87b5d52e26a223c7869.tar.gz PythonPractice-a3d3368d9f024052632dc87b5d52e26a223c7869.tar.bz2 PythonPractice-a3d3368d9f024052632dc87b5d52e26a223c7869.zip |
interator / generators exmaples
Diffstat (limited to 'iterator.py')
-rw-r--r-- | iterator.py | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/iterator.py b/iterator.py new file mode 100644 index 0000000..2b1e14e --- /dev/null +++ b/iterator.py @@ -0,0 +1,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() |