__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

posted on 2020-05-10 17:46  Manuel  阅读(162)  评论(0编辑  收藏  举报