为什么在使用__getitem__进行迭代时会调用__len__而不使用结果? [英] Why __len__ is called and the result is not used when iterating with __getitem__?
本文介绍了为什么在使用__getitem__进行迭代时会调用__len__而不使用结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下示例:
import random
class Class1:
def __getitem__(self, item):
print('getitem', item)
result = random.randint(0, 10)
if not result:
raise IndexError
return result
class Class2(Class1):
def __len__(self):
print('len', 3)
return 3
print(list(Class1()))
print(list(Class2()))
输出:
getitem 0
getitem 1
[10]
len 3
getitem 0
getitem 1
getitem 2
getitem 3
getitem 4
[8, 10, 2, 10]
因此,当遍历Class1()
时,没有__len__
,但是代码可以正常工作.当Class2()
中存在__len__
时,将调用它,但根本不使用结果3
,则在获得3个项目后,迭代将继续.我的问题是:为什么调用__len__
?如果结果被忽略,则没有理由调用它.
So, when iterating through Class1()
there is no __len__
but the code works correctly. When there is __len__
in Class2()
it is called but the result 3
is not used at all, the iteration continues after getting 3 items. My question is: why __len__
is called? There is no reason to call it if the result is ignored.
推荐答案
查看全文