为什么在类上定义__getitem__使其可迭代?
例如,如果我写:
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
...
我真的希望看到“对于cb中的k:”返回的错误:
如果查看定义迭代器的PEP234,它会显示:
1. An object can be iterated over with "for" if it implements
__iter__() or __getitem__().
2. An object can function as an iterator if it implements next().
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句