Python如何自定义迭代器和可迭代对象

什么是迭代器和可迭代对象

迭代器:凡是实现了__iter__()__next__()(python2.x是next())方法的对象就是迭代器

可迭代对象:凡是能返回迭代器对象的对象就是可迭代对象
内建函数iter()会调用__iter__()来获取迭代器对象,所以可迭代对象必须实现__iter__()

自定义迭代器

class OddIterator(object):
    """Iterator to return all
        odd numbers"""

    def __init__(self, max):
        self.max = max
        self.num = 1

    def __iter__(self):
        return self

    def __next__(self):    # python 2.x 改成 next(self)
        if self.num <= self.max:
            num = self.num
            self.num += 2
            return num
        else:
            raise StopIteration

测试

>>> i = OddIterator(5)
>>> next(i)
1
>>> next(i)
3
>>> next(i)
5

迭代器可以直接调用next()方法

自定义可迭代对象

class OddNumber(object):
    def __init__(self, max):
        self.max = max

    def __iter__(self):
        return InfIter(self.max)

测试

>>> i = OddNumber(5)
>>> next(i)
Traceback (most recent call last):
  File "test.py", line 53, in 
    print next(i)
TypeError: instance has no next() method

因为OddNumber是可迭代对象,而不是一个迭代器,所以无法直接调用next()方法,必须先调用内建函数iter()获取迭代器

>>> o = OddNumber(5)
>>> i = iter(o)
>>> next(i)
1
>>> next(i)
3
>>> next(i)
5

你可能感兴趣的:(Python如何自定义迭代器和可迭代对象)