迭代器对象
最编程
2024-01-13 20:49:33
...
首先来看迭代器对象的定义:
- 类中定义了__iter__和__next__方法
- __iter__方法返回self,也就是自身
- __next__方法返回下一个数据,如果没有数据了,则要返回StopIteration的异常(一定要定义什么时候结束迭代,否则就会像没有break的while True循环一样,一直进行下去)
举个例子:
class ItRange():
def __init__(self,num):
self.num = num
self.counter = -1 # 注意,counter是从-1开始的,所以第一次调用__next__函数,会返回0
def __iter__(self):
return self
def __next__(self):
self.counter += 1
if self.counter == self.num: # 如果迭代次数超过num,则触发异常StopIteration,停止迭代,并返回属性counter
raise StopIteration()
return self.counter
ItRange这个类满足了上述的三点要求,是一个迭代器对象。
obj = ItRange(3) # 设置迭代次数上限是3
print(next(obj)) # 输出0, 等价于 obj.__next__() 都是在调用obj这个实例中的__next__方法,输出下一个数据
print(next(obj)) # 输出1
print(next(obj)) # 输出2
print(next(obj)) # 由于迭代次数上限是3,所以第四次调用__next__方法时,会报错如下
'''
Traceback (most recent call last):
File "g:\Python Learner\app.py", line 1278, in <module>
print(next(obj)) # ���ڵ�������������3�����Ե��Ĵε���__next__����ʱ�����������
File "g:\Python Learner\app.py", line 1271, in __next__
raise StopIteration()
StopIteration
'''
迭代器对象是如何与for循环结合使用的:
obj2 = ItRange(3)
for item in obj2: # 首先,会调用__iteer__方法,返回self本身,然后再反复执行next(对象),在遇到异常StopIteration的时候终止循环
print(item)
# 输出结果是分行的 0 1 2