在以下代码中:
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 个元素? (如果我增加它工作正常)
相关分类