iter2.py 490 B

1234567891011121314151617181920212223
  1. # user defined iterator used in something other than a for loop
  2. class MyStopIteration(StopIteration):
  3. pass
  4. class myiter:
  5. def __init__(self, i):
  6. self.i = i
  7. def __iter__(self):
  8. return self
  9. def __next__(self):
  10. if self.i == 0:
  11. raise StopIteration
  12. elif self.i == 1:
  13. raise StopIteration(1)
  14. elif self.i == 2:
  15. raise MyStopIteration
  16. print(list(myiter(0)))
  17. print(list(myiter(1)))
  18. print(list(myiter(2)))