fork download
  1. #!/usr/bin/env python3
  2.  
  3.  
  4. class Obj(): # Итерируемый объект
  5. def __init__(self, word):
  6. self.word = word
  7.  
  8. def __iter__(self):
  9. return Iterator(self.word)
  10.  
  11. class Iterator: # Итератор
  12. def __init__(self, word):
  13. self.word = word
  14. self.index = 0
  15.  
  16. def __next__(self):
  17. try:
  18. letter = self.word[self.index]
  19. self.index += 1
  20. return letter
  21. except IndexError:
  22. raise StopIteration()
  23.  
  24. def __iter__(self):
  25. return self
  26.  
  27.  
  28. obj = Obj('sergey')
  29. it = iter(obj)
  30.  
  31. print(it.__next__())
  32. print(it.__next__())
  33. print(it.__next__())
  34. print(it.__next__())
  35. print(it.__next__())
  36. print(it.__next__())
  37.  
  38. print(it.__iter__())
  39.  
  40.  
Success #stdin #stdout 0.03s 63516KB
stdin
Standard input is empty
stdout
s
e
r
g
e
y
<__main__.Iterator instance at 0x00002b74ee79aaa0>