Guest User

Untitled

a guest
Dec 18th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. class Squares:
  2. def __init__(self, n):
  3. self.n = n
  4.  
  5. def __iter__(self):
  6. return self.SquaresIterator(self.n)
  7.  
  8. class SquaresIterator:
  9. def __init__(self, n):
  10. self.n = n
  11. self.i = 0
  12.  
  13. def __iter__(self):
  14. return self
  15.  
  16. def __next__(self):
  17. if self.i >= self.n:
  18. raise StopIteration
  19.  
  20. result = self.i ** 2
  21. self.i += 1
  22. return result
  23.  
  24. sq_class = Squares(5)
  25. list(sq_class)
  26. [0, 1, 4, 9, 16]
  27. # calling again will create a new iterator
  28. list(sq_class)
  29. [0, 1, 4, 9, 16]
  30.  
  31. def squares(n):
  32. for i in range(n):
  33. yield i ** 2
  34.  
  35. sq_gen = squares(5)
  36. list(sq_gen)
  37. [0, 1, 4, 9, 16]
  38. # calling again will return empty [] is OK, generator exhausted.
  39. list(sq_gen)
  40. []
  41.  
  42. def Squares(n):
  43. def inner():
  44. return squares_gen(n)
  45.  
  46. def squares_gen(n):
  47. for i in range(n):
  48. yield i ** 2
  49.  
  50. return inner
  51.  
  52. sq_closure = Squares(5)
  53. list(sq_closure())
  54. [0, 1, 4, 9, 16]
  55. # calling again the inner will create a new generator so it is not exhausted
  56. list(sq_closure())
  57. [0, 1, 4, 9, 16]
  58.  
  59. def Squares(n):
  60. def inner():
  61. return squares_gen(n)
  62.  
  63. def squares_gen(n):
  64. for i in range(n):
  65. yield i ** 2
  66.  
  67. inner.__iter__ = lambda : squares_gen(n)
  68. return inner
  69.  
  70. sq_closure = Squares(5)
  71. list(sq_closure)
  72.  
  73. ---------------------------------------------------------------------------
  74. TypeError Traceback (most recent call last)
  75. <ipython-input-13-beb02e61ccfb> in <module>
  76. ----> 1 for i in sq:
  77. 2 print(i)
  78.  
  79. TypeError: 'function' object is not iterable
Add Comment
Please, Sign In to add comment