Indexable Class
We require to implement __getitem__
method to make class indexable.
class A:
def __init__(self):
self.items = [1, 2, 3, 4]
def __getitem__(self, i):
if i >= len(self.items):
raise IndexError
return self.items[i]
Now, we can use instance of class A
with for
loop.
a = A()
for i in a:
print(i)
for
loop works both with iterable and indexable objects. In case of indexable objects, it waits for IndexError
exception to stop and in the case of iterable, it requires StopIteration
.