# Python实现自定义迭代器类

Python里迭代器用法如下，主要用到了iter()和next()两个方法

```>>> l = [1, 3, 5, 7, 9]
>>> iter = iter(l)
>>> next(iter)
1
>>> next(iter)
3
>>> next(iter)
5
>>> next(iter)
7
>>> next(iter)
9
>>> next(iter)
Traceback (most recent call last):
File "", line 1, in
StopIteration```

`#!/usr/bin/env python3# -*- coding: utf-8 -*-# Time : 2019/12/27 11:13 下午# Auth : lihui# File : my_iter.pyl = [1, 3, 5, 7, 9]it = iter(l)while True:    try:        print(next(it))    except StopIteration:        break`

iter()：将参数对象转换为迭代器对象

next()：从迭代器对象中取出下一项

`#!/usr/bin/env python3# -*- coding: utf-8 -*-# Time : 2019/12/27 11:13 下午# Auth : lihui# File : my_iter.pyclass Reverse:    def __init__(self, data):        self.data = data        self.index = len(data)    def __iter__(self):        return self    def __next__(self):        if self.index == 0:            raise StopIteration        self.index = self.index - 1        return self.data[self.index]if __name__ == '__main__':    l = [1, 3, 5, 7, 9]    rev = Reverse(l)    while True:        try:            print(next(rev))        except StopIteration:            break`

```>>> from my_iter import Reverse
>>> l = [1, 3, 5, 7, 9]
>>> rev = Reverse(l)
>>> next(rev)
9
>>> next(rev)
7
>>> next(rev)
5
>>> next(rev)
3
>>> next(rev)
1
>>> next(rev)
Traceback (most recent call last):
File "", line 1, in
File "/Users/lihui/Documents/Python/iter/my_iter.py", line 18, in __next__
raise StopIteration
StopIteration```

OVER