python协程初步---一个迭代器的实现
2020-12-13 16:49
标签:site next cti ble rom 方法 print def pass 一般认为迭代器就是实现了两个方法__iter__和__next__ 输出结果: 通过在mycoach类的方法__iter__中返回classiterable实现了mycoach和classiterable类之间的联系 输出结果: 输出结果: python协程初步---一个迭代器的实现 标签:site next cti ble rom 方法 print def pass 原文地址:https://www.cnblogs.com/saintdingspage/p/11621820.html
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 "无法被迭代")
类对象可以被迭代
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.countlen(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 "无法被迭代")
陈培昌
程劲
徐晓冬
类对象可以被迭代
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.countlen(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 "无法被迭代")
陈培昌
程劲
徐晓冬
类对象可以被迭代