阅读背景:

面向对象-迭代器

来源:互联网 

创建一个迭代器的类

class Foo:
    def __init__(self,n):
        self.n = n
    def __iter__(self): #将对象变成一个可迭代对象
        return self

    def __next__(self):  #迭代器需要一个next方法
        if self.n == 100:
            raise StopIteration('终止')
        self.n += 1
        return self.n

f1 = Foo(10)

for i in f1: #iter(f1) == f1.__iter__()
    print(i)

'''
11
12
13
14
15
16
17
18
19
...
'''class Foo:
    def __init__(self,n)



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: