python-代码自定义迭代器

自定义可迭代对象

class Studentlist(object):
def init(self):
self.list_item = []
def append_item(self,name):
self.list_item.append(name)
def func(self):
#获取Studentlist对象的迭代器
stu_iter = iter(stu)
print(next(stu_iter))
print(next(stu_iter))
print(next(stu_iter))
print(next(stu_iter))
print(next(stu_iter))
# 通过iter 方法返回一个迭代器
def iter(self):
stu = StuIterable(self.list_item)
return stu # 返回迭代器

自定义迭代器

#一个实现了__iter__方法和__next__方法的对象,就是迭代器。
class StuIterable(object):
def init(self,list_item):
self.list_item = list_item
self.current_index = 0 #定义变量,记录下标位置
#重写next 方法返回数据
def next(self):
if self.current_index self.current_index+=1
return self.list_item[self.current_index-1]
# 本身是一个迭代器 所以返回自己就好
def iter(self):
return self
#创建Studentlist对象
stu = Studentlist()
stu.append_item(“小花”)
stu.append_item(“小爱”)
stu.append_item(“小红”)
stu.append_item(“小丽”)
stu.append_item(“小强”)
stu.func()

你可能感兴趣的:(python-代码自定义迭代器)