鱼C论坛

 找回密码
 立即注册
查看: 1865|回复: 1

关于iter()方法

[复制链接]
发表于 2022-7-28 23:06:18 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 青出于蓝 于 2022-7-29 07:10 编辑

想问关于iter方法的第二种使用,我以下的代码是否get到了精髓,或者说是多此一举呢
class Iter:
    def __init__(self):
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        self.count += 1
        if self.count > 3:
            raise StopIteration
        return self.count


a = Iter()
b = iter(a.__next__, 10)
print(next(b))
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-7-29 00:55:45 | 显示全部楼层
本帖最后由 suchocolate 于 2022-7-29 01:03 编辑

__next__里定死了3,外面用10没有意义。不如这样:
class Iter:
    def __init__(self, limit=1):
        self.count = 0
        self.limit = limit

    def __iter__(self):
        return self

    def __next__(self):
        self.count += 1
        if self.count > self.limit:
            raise StopIteration
        return self.count


a = Iter(3)
try:
    while True:
        print(next(a))
except Exception as e:
    print(e)
print('=' * 20)
a = Iter(10)
try:
    while True:
        print(next(a))
except Exception as e:
    print(e)
    

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +3 收起 理由
python爱好者. + 5 + 5 + 3 鱼C有你更精彩^_^

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-28 10:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表