我有一个创建建筑的小班.我想更多地了解国际热核实验堆.以下作品:
class Building(object): def __init__(self, floors): self._floors = [None] * floors def __setitem__(self, floor_number, data): self._floors[floor_number] = data def __getitem__(self, floor_number): return self._floors[floor_number] def __iter__(self): for floor_number in self._floors: yield self._floors[floor_number] building1 = Building(9) # Construct a building with 9 floors building1[0] = 'Reception' building1[1] = 'ABC Corp' building1[2] = 'DEF Inc' building1[3] = 'Apple' building1[4] = 'Cisco' building1[5] = 'Microsoft' building1[6] = 'Dell' building1[7] = 'EMC' building1[8] = 'HPE' ''' for floor in building1: print(building1[floor]) ''' print(building1[6]) Dell
但如果我取消注释for循环,我会得到这个:
Traceback (most recent call last): File "C:/Users/Mark/PycharmProjects/main/main.py", line 28, infor floor in building1: File "C:/Users/Mark/PycharmProjects/main/main.py", line 13, in __iter__ yield self._floors[floor_number] TypeError: list indices must be integers or slices, not str
我知道列表索引必须是整数.我没有得到的是为什么这个for循环违反了这个限制.
我想要做的是运用iter协议并打印出建筑物的每个楼层,而不仅仅是特定楼层.
你误解了for
循环的作用; 你没有索引,你在列表中有你的实际值.只是屈服于:
for contents in self._floors: yield contents
您需要在外循环中执行相同的操作:
for contents in building1: print(contents)
Python for
循环是Foreach循环,您迭代值而不是索引.
您的__iter__
方法可以只返回列表的迭代器,而不是循环,有效地委托给iter()
您生成的列表迭代器:
def __iter__(self): return iter(self._floors)