为了账号安全,请及时绑定邮箱和手机立即绑定

Python 迭代器 - For i in

Python 迭代器 - For i in

qq_笑_17 2021-08-05 16:57:49
在以下代码中:class Box:    def __init__(self):        self.volume = []        self.index = -1    def add_item(self, item):        self.volume.append(item)    def __iter__(self):        return self    def __next__(self):        # self.index +=1     NOTE - It is commented         if self.index >= len(self.volume):            raise StopIteration        return self.volume[self.index]class Item:    def __init__(self, name, weight):        self.name = name        self.weight = weight b = Box()b.add_item(Item('Cat', 5))b.add_item(Item('Nintendo Switch', 1))b.add_item(Item('Potatoes', 2))for item in b:    print('The {} weighs {} kg'.format(item.name.lower(), item.weight))所以我们创建了一个 Box 类型的对象 'b' 并向其添加三个项目。问题 1) - b 中的项目是什么意思?它指的是什么?b 里有什么?问题 2) -假设它指的是我们添加到其中的三个项目。为什么它会继续陷入无限循环:马铃薯重 2 公斤而不去其他 2 个元素? (如果我增加它工作正常)
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 267 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号