__getitem__ 在 python 中重载 [英] __getitem__ overloading in python
问题描述
我试图理解 python 中的运算符重载,我编写了一个小程序,它重载 __getitem__()
方法并调用 for 循环:
类 Ovl:数据 = [1,2,3,4,5]def __getitem__(self, index):返回Hiii"x=Ovl()对于 x 中的项目:打印项目
这个程序进入无限循环打印Hiii".我想知道背后的原因.
根据 object.__getitem__
注意,
注意:for
循环期望对于非法索引IndexError
将引发 以允许正确检测到顺序.
<预><代码>>>>班级:... 数据 = [1,2,3,4,5]... def __getitem__(self, index):...如果指数 >= 5:...引发 IndexError('End')...返回Hiii"...>>>x=Ovl()>>>>>>对于 x 中的项目:...打印项目...嗨嗨嗨嗨嗨
I am trying to understand the operator overloading in python and I have written a small programs which overloads __getitem__()
method and calls a for loop:
class Ovl:
data = [1,2,3,4,5]
def __getitem__(self, index):
return "Hiii"
x=Ovl()
for item in x:
print item
This program goes in to a infinite for loop printing "Hiii". I would like to know the reason behind it.
According to the object.__getitem__
NOTE,
NOTE:
for
loops expect that anIndexError
will be raised for illegal indexes to allow proper detection of the end of the sequence.
>>> class Ovl:
... data = [1,2,3,4,5]
... def __getitem__(self, index):
... if index >= 5:
... raise IndexError('End')
... return "Hiii"
...
>>> x=Ovl()
>>>
>>> for item in x:
... print item
...
Hiii
Hiii
Hiii
Hiii
Hiii
这篇关于__getitem__ 在 python 中重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!