class listDemo: def __init__(self): self.__date=[] self.__step = 0 def __next__(self): if self.__step <= 0: raise StopIteration self.__step -= 1 #返回下一个元素 return self.__date[self.__step] def __iter__(self): #实例对象本身就是迭代器对象,因此直接返回 self 即可 return self #添加元素 def __setitem__(self,key,value): self.__date.insert(key,value) self.__step += 1 mylist = listDemo() mylist[0]=1 mylist[1]=2 for i in mylist: print (i)程序执行结果为:
2
1
iter(obj[, sentinel])
其中,obj 必须是一个可迭代的容器对象,而 sentinel 作为可选参数,如果使用此参数,要求 obj 必须是一个可调用对象,具体功能后面会讲。# 将列表转换为迭代器 myIter = iter([1, 2, 3]) # 依次获取迭代器的下一个元素 print(myIter.__next__()) print(myIter.__next__()) print(myIter.__next__()) print(myIter.__next__())运行结果为:
1
2
3
Traceback (most recent call last):
File "C:\Users\mengma\Desktop\demo.py", line 7, in <module>
print(myIter.__next__())
StopIteration
class listDemo: def __init__(self): self.__date=[] self.__step = 0 def __setitem__(self,key,value): self.__date.insert(key,value) self.__step += 1 #是该类实例对象成为可调用对象 def __call__(self): self.__step-=1 return self.__date[self.__step] mylist = listDemo() mylist[0]=1 mylist[1]=2 #将 mylist 变为迭代器 a = iter(mylist,1) print(a.__next__()) print(a.__next__())程序执行结果为:
2
Traceback (most recent call last):
File "D:\python3.6\1.py", line 20, in <module>
print(a.__next__())
StopIteration
本文链接:http://task.lmcjl.com/news/7343.html