Advertisement
furas

Python2 - iterator

Apr 29th, 2017
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.72 KB | None | 0 0
  1. #! python2
  2.  
  3. class Counter(object):
  4.  
  5.     def __init__(self, low, high):
  6.         self.current = low
  7.         self.high = high
  8.  
  9.     def __iter__(self):
  10.         'Returns itself as an iterator object'
  11.         return self
  12.  
  13.     def next(self):
  14.         'Returns the next value till current is lower than high'
  15.         if self.current > self.high:
  16.             raise StopIteration
  17.         else:
  18.             self.current += 1
  19.             return self.current - 1
  20.  
  21. n = 1000
  22. #n = 10 # easier to check result
  23.  
  24. i = Counter(0, n)
  25. for v in i:
  26.     print(v)
  27.  
  28. #------------------------------------------
  29.    
  30. print('----------------------')
  31.  
  32. i = Counter(0, n)
  33.  
  34. print(next(i)) # 0
  35. print(next(i)) # 1
  36. print(next(i)) # 2
  37. #etc.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement