首页 > 编程语言 > 详细

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

时间:2019-10-04 12:39:42      阅读:56      评论:0      收藏:0      [点我收藏+]

一般认为迭代器就是实现了两个方法__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 "无法被迭代")

输出结果:

陈培昌
程劲
徐晓冬
类对象可以被迭代

 

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

原文:https://www.cnblogs.com/saintdingspage/p/11621820.html

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