class BothiterAndnext: def __init__(self): self.count = 0 # 初始化计数器,记录已迭代次数 self.max_count = 3 # 设定最大迭代次数(可根据需求修改) def __iter__(self): return self # 迭代器必须返回自身 def __next__(self): if self.count < self.max_count: # 未达到最大次数时继续迭代 self.count += 1 # 计数器+1 return 1111 else: raise StopIteration # 达到次数后,抛出异常终止迭代 bo = BothiterAndnext() for i in bo: print(i)
Python 的 for 循环本质是不断调用 next ,直到捕获到 StopIteration 异常才停止。因此,只要在 next 里合理控制“何时抛异常”,就能精准控制迭代行为~