1.自定义迭代器
# 迭代器
# 自定义迭代器
# Iterable :判断对象是否为迭代对象
# Iterator : 判断对象是否是迭代器
from collections.abc import Iterable
from collections.abc import Iterator
class List(object):
def __init__(self):
self.items=[]
pass
def __iter__(self):
return listIterator()
def add(self,item):
self.items.append(item)
pass
class listIterator(object):
def __init__(self):
pass
def __iter__(self):
pass
def __next__(self):
print("__next__")
pass
list=List()
list.add(1)
list.add(2)
iter_list=iter(list)
print(isinstance(list,Iterable)) # 判断是否是可迭代对象
print(isinstance(iter_list,Iterator)) #判断是否是迭代器
print(next(iter_list))
输出:
True
True
__next__
None
Process finished with exit code 0
自定义一个迭代器
# 自定义一个迭代器
class List(object):
def __init__(self):
self.items=[]
self.current=0
pass
def __iter__(self):
return self
def __next__(self):
print("__next__")
if self.current<len(self.items):
item=self.items[self.current]
self.current+=1
return item
else:
self.current = 0
raise StopIteration #抛出异常
# return 200
pass
def add(self, other):
self.items.append(other)
pass
if __name__=="__main__":
print("main")
list=List()
list.add(1)
list.add(2)
iter_list=iter(list)
# print(next(iter_list))
for t in iter_list:
print(t)
for t in iter_list:
print(t)
3. for...in...
循环的本质
- 先调用
iter()
函数,它会自动调用可迭代对象中的__iter__
方法,此方法返回这个可迭代对象的 迭代器对象 - 对获取到的迭代器不断调用
next()
函数,它会自动调用迭代器中的__next__
方法来获取下一个值 - 当遇到
StopIteration
异常后循环结束
# 练习
class LIST(object):
def __init__(self):
self.items=[]
self.current=0
pass
def __iter__(self):
return self
pass
def __next__(self):
if self.current<len(self.items):
item=self.items[self.current]
self.current+=1
return item
else:
self.current=0
raise StopIteration
pass
def add(self,other):
self.items.append(other)
pass
if __name__=="__main__":
my_list=LIST()
my_list.add(1)
my_list.add(2)
iter_list=iter(my_list)
# for i in iter_list:
# print(i)
#
# for i in iter_list:
# print(i)
tmp=list(my_list)
print(tmp)
tmp1=tuple(my_list)
print(tmp1)
2023-04-25
网友评论