what is iterable object in python code example
Example: python make class iterable
"""
Example for a Class that creates an iterator for each word in a sentence
The keyword 'yield' is key (no pun intended) to the solution. It works the
same as return with the exception that on the next call to the function it
will resume where it left off
"""
class WordIterator:
def __init__(self, string, seperator = ' ') -> None:
self.string = string
self.seperator = seperator
def __iter__(self):
this_iter_result = ''
for char in self.string:
if char != self.seperator:
this_iter_result += char
elif this_iter_result != '':
yield this_iter_result
this_iter_result = ''
if this_iter_result != '':
yield this_iter_result
wrd_iter = WordIterator('This is a sentence')
for i in wrd_iter:
print (i, end=',')