迭代器和可迭代对象
import re import reprlib RE_WORD = re.compile('\w+') class SentenceIterator: def __init__(self, words): self.words = words self.index = 0 def __next__(self): try: word = self.words[self.index] except IndexError: raise StopIteration() self.index += 1 return word def __iter__(self): # 其实可以不用写 return self class Sentence: def __init__(self, text): self.text = text self.words = RE_WORD.findall(text) def __repr__(self): return 'Setence(%s)' % reprlib.repr(self.text) def __iter__(self): return SentenceIterator(self.words) s4 = Sentence('pig and pepper') it = iter(s4) print(next(it)) print(next(it)) print(next(it)) ''' 注意:可迭代对象内部并不实现__next__方法,因为每次调用iter(my_iterable)都需要生成一个新的迭代器 '''
12