鱼C论坛

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

关于iter()方法

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

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

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

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

想问关于iter方法的第二种使用,我以下的代码是否get到了精髓,或者说是多此一举呢

  1. class Iter:
  2.     def __init__(self):
  3.         self.count = 0

  4.     def __iter__(self):
  5.         return self

  6.     def __next__(self):
  7.         self.count += 1
  8.         if self.count > 3:
  9.             raise StopIteration
  10.         return self.count


  11. a = Iter()
  12. b = iter(a.__next__, 10)
  13. print(next(b))
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

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

  5.     def __iter__(self):
  6.         return self

  7.     def __next__(self):
  8.         self.count += 1
  9.         if self.count > self.limit:
  10.             raise StopIteration
  11.         return self.count


  12. a = Iter(3)
  13. try:
  14.     while True:
  15.         print(next(a))
  16. except Exception as e:
  17.     print(e)
  18. print('=' * 20)
  19. a = Iter(10)
  20. try:
  21.     while True:
  22.         print(next(a))
  23. except Exception as e:
  24.     print(e)
  25.    
复制代码

评分

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

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-27 18:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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