python--迭代器的实现

#!/usr/local/python/bin/python3
"""
一个迭代器的例子
"""

class exsample(object):
    """
    exsample 类实现迭代功能
    __iter__返回一个迭代器
    __next__定义每一次迭代要返回的值
    """
    def __init__(self,counter=10):
        self.index=0
        self.counter=counter

    def __iter__(self):
        return self

    def __next__(self):
        if self.index <self.counter:
            self.index=self.index+1
            return self.index -1
        else:
            raise StopIteration()


if __name__=="__main__":
    for x in exsample():
        print(x)
[root@workstudio tmp]# ./main.py 
0
1
2
3
4
5
6
7
8
9
原文地址:https://www.cnblogs.com/JiangLe/p/7191995.html