当前位置:  开发笔记 > 编程语言 > 正文

使用iter协议的类

如何解决《使用iter协议的类》经验,为你挑选了1个好方法。

我有一个创建建筑的小班.我想更多地了解国际热核实验堆.以下作品:

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 
    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协议并打印出建筑物的每个楼层,而不仅仅是特定楼层.



1> Martijn Piet..:

你误解了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)

推荐阅读
mobiledu2402851377
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有