__Getitem__ overload in python

I am trying to understand operator overloading in python, and I wrote small programs that overload the method __getitem__()and call the 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 to endless for the print cycle "Hiii". I would like to know the reason for this.

+4
source share
2 answers

According to object.__getitem__NOTE

NOTE. Loops forexpect a to IndexErrorbe raised for invalid indices to ensure 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
+10
source

__getitem__ - :

>>> x = Ovl()
>>> x[6]
'Hi'
>>> x[8]
'Hi'

for, __iter__ (. : __iter __ (self) (Python)).

, , , __iter__, -, __getitem__ . , __getitem__(0), __getitem__(1), __getitem__(2), ... , .

__getitem__:

def __getitem__(self, index):
    return index, "Hi"

, :

>>> x = Ovl()
>>> for item in x:
    print item 

(0, 'Hi')
(1, 'Hi')
(2, 'Hi')
(3, 'Hi')
(4, 'Hi')
(5, 'Hi')
(6, 'Hi')
...
+1

All Articles