为什么使类可迭代产生这个输出?

时间:2012-02-04 22:38:27

标签: python iterable

  

可能重复:
  Why does defining getitem on a class make it iterable in python?

class b:
    def __getitem__(self, k):
        return k

cb = b()

for k in cb:
    print k

我得到了输出:

0
1
2
3
4
5
6
7
8
.....

迭代b类的实例,发出整数。那是为什么?

(在查看Why does defining __getitem__ on a class make it iterable in python?时看到了上述程序)

1 个答案:

答案 0 :(得分:3)

因为通过将连续索引传递给对象的__getitem__方法,为定义__iter__但不定义__getitem__的对象实现了for循环。见the effbot。 (在IIUC下真正发生的事情有点复杂:如果对象没有提供__iter__,则在对象上调用iter,并且iter返回的迭代器会调用底层对象的__getitem__。)