1. 程式人生 > >面向物件-迭代器

面向物件-迭代器

建立一個迭代器的類

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 Fib:
    def __init__(self):
        self._a = 1
        self._b =1
        print(self._a,self._b,end='  ')
    def __iter__(self):
        return self
    def __next__(self):
        if self._b>1000:
            raise StopIteration("stopd")
        self._a,self._b=self._b,self._a+self._b
        return self._a,self._b
a = Fib()
for i in a:
    print(i[1],end='  ')
'''
1 1  2  3  5  8  13  21  34  55  89  144  233  377  610  987  1597 
'''