1. 当类中定义了__iter__和__next__两个方法;
2. __iter__方法需要返回对象本身,即:self;
3. __next__方法,返回下一个数据,如果没有数据了,则需要抛出一个StopIteration的异常。
# 创建迭代器类
class IT(object):
def __init__(self):
self.counter = 0
def __iter__(self):
return self
def __next__(self):
self.counter += 1
if self.counter == 3:
raise StopIteration()
return self.counter
# 根据类实例化创建一个迭代器对象:
obj1 = IT()
v1 = obj1.__next__()
print(v1)
v2 = next(obj1) # 等价于 v2 = obj1.__next__();next()是python的内置函数,可帮我们自动去执行.__next__()函数python
print(v2)
v3 = next(obj1)
print(v3)
1
2
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_12184\3855014687.py in
22 print(v2)
23
---> 24 v3 = next(obj1)
25 print(v3)
26
~\AppData\Local\Temp\ipykernel_12184\3855014687.py in __next__(self)
10 self.counter += 1
11 if self.counter == 3:
---> 12 raise StopIteration()
13 return self.counter
14
StopIteration:
obj2 = IT()
for item in obj2:
print(item)
1
2
解析:
定义:有yied的函数就叫生成器
## 创建生成器函数
def fun<