TelenkovDmitry 4 meses atrás
pai
commit
c6ffaa4ef6
1 arquivos alterados com 96 adições e 0 exclusões
  1. 96 0
      courses/python_func/closure.py

+ 96 - 0
courses/python_func/closure.py

@@ -0,0 +1,96 @@
+
+
+def multiply(value):
+    def inner(x):
+        return value*x
+    return inner
+
+
+def make_repeater(n):
+    def inner(str):
+        return(str*n)
+    return inner
+
+'''
+def create_accumulator():
+    s = 0
+    def inner(x):
+        nonlocal s
+        s += x
+        return s
+    return inner
+'''
+    
+
+def create_accumulator(start_value=0):
+    s = start_value
+    def inner(x):
+        nonlocal s
+        s += x
+        return s
+    return inner
+
+
+def countdown(x):
+    counter = start = x
+    def inner():
+        nonlocal counter
+        if counter <= 0:
+            print(f"Превышен лимит, вы вызвали более {start} раз")
+        else:
+            print(counter)
+        counter -= 1      
+    return inner
+
+
+def count_calls():
+    counter = 0
+    def inner():
+        inner.total_calls += 1
+        return inner.total_calls
+    setattr(inner, 'total_calls', 0)
+    return inner
+
+
+def my_func(a):
+    def inner(x):
+        return x - a
+    return inner
+
+
+def main():
+    # x = my_func(10)
+    # print(x(5))
+
+    # f_2 = multiply(2)
+    # print(f_2(5))
+    # print(f_2(15))
+
+    # repeat_2 = make_repeater(2)
+    # print(repeat_2('Pizza'))
+    # print(repeat_2('Pasta'))
+
+    # summator_1 = create_accumulator()
+    # print(summator_1(1)) # печатает 1
+    # print(summator_1(5)) # печатает 6
+    # print(summator_1(2)) # печатает 8
+
+    # summator_2 = create_accumulator()
+    # print(summator_2(3)) # печатает 3
+    # print(summator_2(4)) # печатает 7
+
+    # summator_1 = create_accumulator(100)
+    # print(summator_1(1)) # печатает 101
+    # print(summator_1(5)) # печатает 106
+    # print(summator_1(2)) # печатает 108
+
+    counter = count_calls()
+    counter()
+    counter()
+    print(counter.total_calls)
+    counter()
+    print(counter.total_calls)
+
+
+if __name__ == '__main__':
+    main()