码迷,mamicode.com
首页 > 其他好文 > 详细

__iter__和__next__实现迭代器协议

时间:2020-05-10 19:32:08      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:star   utf-8   print   实现   div   iterator   color   art   __iter__   

__iter__()将对象转换为可迭代对象,__next__()返回实现迭代

#_*_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 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) 

 

斐波那契数列:

#1,1,2,3,5,8,13,21...
class Foo:
    def __init__(self,star,end):
        self.mid = 0
        self.star = star
        self.end = end
    def __iter__(self):
        return self
    def __next__(self):
        self.mid,self.star = self.star,self.mid+self.star
        if self.star >= self.end:
            raise  StopIteration
        return self.star

f1=Foo(1,1000)
for i in f1:
    print(i)

 

1

__iter__和__next__实现迭代器协议

标签:star   utf-8   print   实现   div   iterator   color   art   __iter__   

原文地址:https://www.cnblogs.com/Manuel/p/12864345.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!