fig2.py 426 B

123456789101112131415
  1. class Iterable(object):
  2. def __init__(self):
  3. self.arr = range(10)
  4. def __iter__(self):
  5. return iter(self.arr)
  6. def __getitem__(self, index):
  7. """ If Python tried to iterate with this method we'd be stuck in an infinite loop (because `__getitem__` never raises an `IndexError`) """
  8. return self.arr[0]
  9. if __name__ == "__main__":
  10. # Prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  11. print [i for i in Iterable()]