zoukankan      html  css  js  c++  java
  • __next__和__iter__实现迭代器协议

    # __next__和__iter__实现迭代器协议
    class Foo:
        def __init__(self, n):  # 初始化
            self.n = n
    
        def __iter__(self): # 定义类的__iter__方法,实例化时就为一个可迭代对象
            return self
    
        def __next__(self): # 定义类的__next__方法,并在其中设置抛出StopIteration的条件
            self.n += 1
            if self.n > 100:
                raise StopIteration
            return self.n
    
    f1 = Foo(10)
    
    for i in f1:    # 本质上就是iter(f1)==f1.__iter__()
        print(i)
    
    
    # 迭代器协议实现斐波那契数列
    
    class Fib:
        def __init__(self):  # 初始化
    
            self.a = 0
            self.b = 1
    
        def __iter__(self):  # 定义类的__iter__方法,实例化时就为一个可迭代对象
            return self
    
        def __next__(self):  # 定义类的__next__方法,并在其中设置抛出StopIteration的条件
            self.a, self.b = self.b, self.a + self.b
    
            if self.a > 10000:
                raise StopIteration
            return self.a
    
    
    fib = Fib()
    print(next(fib))
    print(next(fib))
    print(next(fib))
    print(next(fib))
    print(next(fib))
    print('----------------------')
    for i in fib:
        print(i)
  • 相关阅读:
    1058 A+B in Hogwarts (20)
    1046 Shortest Distance (20)
    1061 Dating (20)
    1041 Be Unique (20)
    1015 Reversible Primes (20)(20 分)
    pat 1027 Colors in Mars (20)
    PAT 1008 Elevator (20)
    操作系统 死锁
    Ajax的get方式传值 避免& 与= 号
    让IE浏览器支持CSS3表现
  • 原文地址:https://www.cnblogs.com/dangrui0725/p/9470997.html
Copyright © 2011-2022 走看看