# 迭代器
# 创捷迭代器类型
# 1、当类中定义__iter__和__next__两个方法;
# 2、__iter__方法需要返回对象本身,即self;
# 3、__next__返回下一个数值,如果没有需要抛出一个StopIteration的异常
# 如果一个类中有一个__iter__方法并返回一个迭代器对象,则我们称这个类创建的对象是可迭代对象
class IT(object):
def __init__(self):
self.counter = 0
def __iter__(self):
return self
def __next__(self):
self.counter +=1
if self.counter == 5:
raise StopIteration()
return self.counter
obj = IT()
v1 = next(obj)
print(v1) # 输出1
v2 = next(obj)
print(v2) # 输出2
v3 = next(obj)
print(v3) # 输出3
v4 = next(obj)
print(v4) # 输出4
obj1 = IT()
for item in obj1:
print(item) # 输出1 2 3 4
# 可迭代对象是可以被for循环