Python for循环与__getitem__的关系记录
一个类里面如果由__iter__for循环就是找它取,没有的话就会找__getitem__ 前面一笔看过没有留心具体的执行情况。 In [169]: class Foo: ...: def __getitem__(self, pos): ...: print(pos) ...: return range(10)[pos] ...: In [172]: for i in f: ...: ... ...: ...: 0 1 2 3 4 5 6 7 8 9 10 从代码可以看出,如果没有报错或者设置显式的条件,这个for循环会无线循环。 我现在设置一个显式的设置。 In [173]: class Foo: ...: def __getitem__(self, pos): ...: if pos >5: ...: raise StopIteration ...: print(pos) ...: return range(10)[pos] ...: In [177]: for i in f: ...: ... ...: 0 1 2 3 4 5 将错误设置为IndexError也可以执行,但TypeError就不行了。 ...: def __getitem__(self, pos): ...: if pos >5: ...: raise IndexError ...: print(pos) .