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

    一. __next__和__iter__实现迭代器协议

    #_*_coding:utf-8_*_
    __author__ = 'Linhaifeng'
    class Foo:
        def __init__(self,x):
            self.x=x
    
        def __iter__(self):
            return self
    
        def __next__(self):
            n=self.x
            self.x+=1
            return self.x
    
    f=Foo(3)
    for i in f:
        print(i)
    
    简单示范
    class Da(object):
    
        def __init__(self,num):
            self.num=num
    
        def __iter__(self):
             return  self
        def __next__(self):
            if self.num>=88:
                raise  StopIteration ("你有一场")
            self.num+=1
            return  self.num
    aa=Da(1)
    
    # for i in aa:
    #     print(i)
    
    bb=aa.__iter__()
    print(bb.__next__())
    print(bb.__next__())
    class Foo:
        def __init__(self,start,stop):
            self.num=start
            self.stop=stop
        def __iter__(self):
            return self
        def __next__(self):
            if self.num >= self.stop:
                raise StopIteration
            n=self.num
            self.num+=1
            return n
    
    f=Foo(1,5)
    from collections import Iterable,Iterator
    print(isinstance(f,Iterator))
    
    for i in Foo(1,5):
        print(i)
    class Range:
        def __init__(self,n,stop,step):
            self.n=n
            self.stop=stop
            self.step=step
    
        def __next__(self):
            if self.n >= self.stop:
                raise StopIteration
            x=self.n
            self.n+=self.step
            return x
    
        def __iter__(self):
            return self
    
    for i in Range(1,7,3): #
        print(i)
    
    练习:简单模拟range,加上步长
    class Fib:
        def __init__(self):
            self._a=0
            self._b=1
    
        def __iter__(self):
            return self
    
        def __next__(self):
            self._a,self._b=self._b,self._a + self._b
            return self._a
    
    f1=Fib()
    
    print(f1.__next__())
    print(next(f1))
    print(next(f1))
    
    for i in f1:
        if i > 100:
            break
        print('%s ' %i,end='')
    
    斐波那契数列
  • 相关阅读:
    attr方法笔记(反射)
    微信小程序的view标签中text如何居中?
    如何在button里面插入图片?
    html如何实现空格?
    margin-left有效果但是margin-top没有用没有效果?如何解决?
    html里button实现跳转事件
    js 字符串切割
    html获取输入框的值
    Uncaught TypeError: Cannot read property ‘split’ of undefined
    日历实现
  • 原文地址:https://www.cnblogs.com/Sup-to/p/11087379.html
Copyright © 2011-2022 走看看