getitem.py 708 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. # create a class that has a __getitem__ method
  2. class A:
  3. def __getitem__(self, index):
  4. print('getitem', index)
  5. if index > 10:
  6. raise StopIteration
  7. # test __getitem__
  8. A()[0]
  9. A()[1]
  10. # iterate using a for loop
  11. for i in A():
  12. pass
  13. # iterate manually
  14. it = iter(A())
  15. try:
  16. while True:
  17. next(it)
  18. except StopIteration:
  19. pass
  20. # this class raises an IndexError to stop the iteration
  21. class A:
  22. def __getitem__(self, i):
  23. raise IndexError
  24. print(list(A()))
  25. # this class raises a non-StopIteration exception on iteration
  26. class A:
  27. def __getitem__(self, i):
  28. raise TypeError
  29. try:
  30. for i in A():
  31. pass
  32. except TypeError:
  33. print("TypeError")