我有一个创建建筑的小班。我想了解更多关于 iter 的信息。以下作品:
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, in <module>
for 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 协议并打印出建筑物的每个楼层,而不仅仅是特定楼层。
答案 0 :(得分:5)
你误解了for
循环的作用;你没有索引,你在列表中有实际值。只是屈服于那些:
for contents in self._floors:
yield contents
你需要在你的外循环中做同样的事情:
for contents in building1:
print(contents)
Python for
循环是Foreach loops,你迭代值而不是索引。
您的__iter__
方法可以只返回列表的迭代器,而不是循环,有效地委托给iter()
为您生成的列表迭代器:
def __iter__(self):
return iter(self._floors)