自定义类实现迭代器

一、

class Foo:
    def __init__(self,n):
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.n == 13:
            raise StopIteration
        self.n += 1
        return self.n

f1 = Foo(10)
for i in f1:   #obj = iter(f1)---->f1.__iter__()
    print(i)   #obj.__next__()

二、迭代器实现斐波那契额数列

class Fib:
    def __init__(self):
        self._a = 1
        self._b = 1

    def __iter__(self):
        return self

    def __next__(self):
        if self._a > 100:
            raise StopIteration
        self._a, self._b = self._b, self._a + self._b
        return self._a

f1 = Fib()
print(next(f1))
print(next(f1))
print("----------->")
for i in f1:
    print(i)

自定义类实现迭代器_第1张图片  

  

转载于:https://www.cnblogs.com/dabai123/p/11629013.html

你可能感兴趣的:(自定义类实现迭代器)