python协程初步---一个迭代器的实现

一般认为迭代器就是实现了两个方法__iter__和__next__

  • 先创建这样一个类
from collections import Iterable
from collections import Iterator

class classiterable(object):
    def __iter__(self):
        pass
    def __next__(self):
        pass


class mycoach(object):
    def __init__(self):
        pass
    def addname(self):
        pass
    def __iter__(self):
        return classiterable()
cpc = mycoach()

print("类对象可以被迭代" if isinstance(cpc,Iterable) else "无法被迭代")

输出结果:

类对象可以被迭代

通过在mycoach类的方法__iter__中返回classiterable实现了mycoach和classiterable类之间的联系

  • 实现classiterator访问mycoach类中的属性
from collections import Iterable
from collections import Iterator

class classiterable(object):
    def __init__(self,obj):
        self.obj = obj
        self.count = 0 #添加一个计数器,确保按顺序遍历数组

    def __iter__(self):
        pass
    def __next__(self):
        #防止迭代过头
        if self.count<len(self.obj.coachname):
            ret = self.obj.coachname[self.count]
            self.count+=1
            return ret
        else:
            raise StopIteration

class mycoach(object):
    def __init__(self):
        self.coachname=[]
    def addname(self,name):
        self.coachname.append(name)
    def __iter__(self):
        return classiterable(self)
cpc = mycoach()
cpc.addname('陈培昌')
cpc.addname('程劲')
cpc.addname('徐晓冬')
for i in cpc:
    print(i)
print("类对象可以被迭代" if isinstance(cpc,Iterable) else "无法被迭代")

输出结果:

陈培昌
程劲
徐晓冬
类对象可以被迭代
  • 完全进化版本---mycoach内部实现__next__魔术方法
class mycoach(object):
    def __init__(self):
        self.coachname=[]
        self.count=0
    def addname(self,name):
        self.coachname.append(name)
    def __iter__(self):
        return self
    def __next__(self):
        if self.count<len(self.coachname):
            ret = self.coachname[self.count]
            self.count+=1
            return ret
        else:
            raise StopIteration


cpc = mycoach()
cpc.addname('陈培昌')
cpc.addname('程劲')
cpc.addname('徐晓冬')
for i in cpc:
    print(i)
print("类对象可以被迭代" if isinstance(cpc,Iterable) else "无法被迭代")

输出结果:

陈培昌
程劲
徐晓冬
类对象可以被迭代
  •  斐伯纳契数列
class mywenwa(object):
    def __init__(self,num):
        self.a,self.b=0,1
        self.count=0
        self.times=num
    def __iter__(self):
        return self
    def __next__(self):
        if self.count <self.times:
            self.a,self.b = self.a+self.b,self.a
            ret = self.b
            return ret
        else:
            raise StopIteration
saiwa = mywenwa(10)
print(next(saiwa))
print(next(saiwa))
print(next(saiwa))
print(next(saiwa))
print(next(saiwa))
print(next(saiwa))
print(next(saiwa))
print(next(saiwa))
print(next(saiwa))
.......

输出结果:

0
1
1
2
3
5
8
13
21
34
55
原文地址:https://www.cnblogs.com/saintdingspage/p/11621820.html