首页 > 其他 > 详细

迭代器协议

时间:2019-03-28 17:52:13      阅读:133      评论:0      收藏:0      [点我收藏+]

1.迭代器协议是指:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个Stopiteration异常,以终止迭代

2.可迭代对象:实现了迭代器协议的对象(如何实现:对象内部定义一个__iter__方法)

技术分享图片
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

# l=list(‘hello‘)
# for i in l:
#     print(i)
f1=Foo(10)
print(f1.__next__())        #11
print(f1.__next__())        #12
print(f1.__next__())        #13
print(f1.__next__())        #StopIteration: 终止了

# for i in f1:      # obj=iter(f1)------------>f1.__iter__()
#      print(i)     #obj.__next_()
View Code

 

技术分享图片
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(next(f1))
print(next(f1))
print(next(f1))
print(==============)
for i in f1:
    print(i)
    
# 1
# 2
# 3
# 5
# 8
# ==============
# 13
# 21
# 34
# 55
# 89
# 144
迭代器协议实现斐波那契数列

 

迭代器协议

原文:https://www.cnblogs.com/wuweixiong/p/10616569.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!