closure.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. def multiply(value):
  2. def inner(x):
  3. return value*x
  4. return inner
  5. def make_repeater(n):
  6. def inner(str):
  7. return(str*n)
  8. return inner
  9. '''
  10. def create_accumulator():
  11. s = 0
  12. def inner(x):
  13. nonlocal s
  14. s += x
  15. return s
  16. return inner
  17. '''
  18. def create_accumulator(start_value=0):
  19. s = start_value
  20. def inner(x):
  21. nonlocal s
  22. s += x
  23. return s
  24. return inner
  25. def countdown(x):
  26. counter = start = x
  27. def inner():
  28. nonlocal counter
  29. if counter <= 0:
  30. print(f"Превышен лимит, вы вызвали более {start} раз")
  31. else:
  32. print(counter)
  33. counter -= 1
  34. return inner
  35. def count_calls():
  36. counter = 0
  37. def inner():
  38. inner.total_calls += 1
  39. return inner.total_calls
  40. setattr(inner, 'total_calls', 0)
  41. return inner
  42. def my_func(a):
  43. def inner(x):
  44. return x - a
  45. return inner
  46. def main():
  47. # x = my_func(10)
  48. # print(x(5))
  49. # f_2 = multiply(2)
  50. # print(f_2(5))
  51. # print(f_2(15))
  52. # repeat_2 = make_repeater(2)
  53. # print(repeat_2('Pizza'))
  54. # print(repeat_2('Pasta'))
  55. # summator_1 = create_accumulator()
  56. # print(summator_1(1)) # печатает 1
  57. # print(summator_1(5)) # печатает 6
  58. # print(summator_1(2)) # печатает 8
  59. # summator_2 = create_accumulator()
  60. # print(summator_2(3)) # печатает 3
  61. # print(summator_2(4)) # печатает 7
  62. # summator_1 = create_accumulator(100)
  63. # print(summator_1(1)) # печатает 101
  64. # print(summator_1(5)) # печатает 106
  65. # print(summator_1(2)) # печатает 108
  66. counter = count_calls()
  67. counter()
  68. counter()
  69. print(counter.total_calls)
  70. counter()
  71. print(counter.total_calls)
  72. if __name__ == '__main__':
  73. main()