__getitem__ 在 python 中重载 [英] __getitem__ overloading in python

查看:90
本文介绍了__getitem__ 在 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 an IndexError 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆