python-迭代器

class Classmate():
def __init__(self):
self.name = list()
self.current = 0
#print(self.name)

def add(self,name):
self.name.append(name)
#print(self.name)


def __iter__(self):
return self#一定要返回为self,或者return 一个含有__iter__和__next__函数的对象



def __next__(self):
#当for循环调用时不会自动增加列表中的值,需要加一个属性进行增加
#
if self.current<len(self.name):
ret = self.name[self.current]
self.current += 1
return ret
else:
raise StopIteration
#当调用时将抛出异常,超过数组的长度
#方法解决:超过数据长度时,主动抛出异常使for循环停止

classmate = Classmate()
classmate.add("张三")
classmate.add("张三1")
classmate.add("张三2")

for i in classmate:
#for循环只能用于可迭代的对象,判断对象是否可迭代,1:需要有__iter__方法以及 __next__方法,其中__iter__方法一定要实现,__next__方法为for循环调用时使用的值
print(i)
posted @ 2019-03-15 17:17  quan54  阅读(108)  评论(0编辑  收藏  举报