首页 新闻 会员 周边

Python 的 for 循环本质是不断调用 next ,直到捕获到 StopIteration 异常才停止

0
[已关闭问题] 关闭于 2026-07-01 13:45
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  里合理控制“何时抛异常”,就能精准控制迭代行为~

*Tesla*的主页 *Tesla* | 老鸟四级 | 园豆:2250
提问于:2026-07-01 13:45
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册