在以下代碼中: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))所以我們創(chuàng)建了一個(gè) Box 類型的對象 'b' 并向其添加三個(gè)項(xiàng)目。問題 1) - b 中的項(xiàng)目是什么意思?它指的是什么?b 里有什么?問題 2) -假設(shè)它指的是我們添加到其中的三個(gè)項(xiàng)目。為什么它會繼續(xù)陷入無限循環(huán):馬鈴薯重 2 公斤而不去其他 2 個(gè)元素? (如果我增加它工作正常)
添加回答
舉報(bào)
0/150
提交
取消