Python迭代器&生成器

迭代器

迭代器学习的关键点在于区分iteratoriterableiterator代表一个对象是一个迭代器(可迭代对象), 而iterable代表该对象可以被迭代

from collections import Iterator, Iterable


class CustomRange:
    """
    custom range()
    """
    def __init__(self, x, y):
        self._x = x
        self._y = y
        self._current = self._x

    def __iter__(self,):
        """
        该方法使对象变成迭代器 使对象支持for ... in的语法 iterator
        """
        return self

    def __next__(self,):
        """
        该方法使对象可以被迭代 iterable
        """
        if self._current > self._y:
            raise StopIteration
        self._current += 1
        return self._current


obj = CustomRange(0, 3)
print(isinstance(obj, Iterator))
print(isinstance(obj, Iterable))
"""
output:
True
True
"""

生成器

生成器也可以被迭代, 生成器不需要实现__next__&__iter__方法, 与迭代器不同的是生成器使用yield返回数据 下次next对象会从yield后面的代码开始执行, 生成器的优点是惰性计算,代码在需要执行的时候才会被被执行

class CatFile:
    def __init__(self, file_name,):
        self._file_name = file_name

    def __call__(self):
        count = 1
        with open(self._file_name, 'r') as file_read:
            for line in file_read:
                yield '第{}行'.format(count)
                yield '\t{}'.format(line.strip())
                count += 1


obj = CatFile('a.txt')
print(obj())
for item in obj():
    print(item)
"""
output:
<generator object CatFile.__call__ at 0x0xxxxxx>
第1行
    qewewqeqwewqeq
第2行
    fwhfewiuhewui
第3行
    ewqrbfehreheb
"""

4 thoughts on “Python迭代器&生成器”

Leave a Reply to Blogger Owner Cancel reply

Your email address will not be published. Required fields are marked *