zoukankan      html  css  js  c++  java
  • 面向对象-迭代器

    创建一个迭代器的类

    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 
    '''
    
  • 相关阅读:
    线程同步锁的使用方式
    EventBus简单封装
    Dagger2不自动生成daggerXXXcomponent
    android mvp模式
    第八天
    单词统计续
    学习进度第十一周
    第七天
    第六天
    第五天
  • 原文地址:https://www.cnblogs.com/chrrydot/p/9822844.html
Copyright © 2011-2022 走看看