完全理解Python迭代对象、迭代器、生成器

2018-08-28  本文已影响0人  __robin

import re
from _collections_abc import Iterable, Iterator


class Sentence:
    def __init__(self, text):
        self.text = text
        self.words = re.compile('\w+').findall(text)

    def __iter__(self):
        return SentenceIterator(self.words)


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


print(issubclass(Sentence, Iterable))
print(issubclass(Sentence, Iterator))
print(issubclass(SentenceIterator, Iterator))

#输出结果:
True
False
True



关系图如下:

容器, 可迭代对象, 迭代器, 生成器关系图

参考文档:容器, 可迭代对象, 迭代器, 生成器关系

上一篇下一篇

猜你喜欢

热点阅读