unknown há 4 meses atrás
pai
commit
1ade0d126b
2 ficheiros alterados com 80 adições e 6 exclusões
  1. 49 6
      courses/python_func/closure.py
  2. 31 0
      courses/python_func/decorator.py

+ 49 - 6
courses/python_func/closure.py

@@ -1,3 +1,5 @@
+from datetime import datetime
+from time import perf_counter, sleep
 
 
 
 
 def multiply(value):
 def multiply(value):
@@ -52,6 +54,37 @@ def count_calls():
     return inner
     return inner
 
 
 
 
+def counter(func):
+    '''Выводит имя и количество вызовов функции'''
+    count = 0
+    def inner(*args, **kwargs):
+        nonlocal count
+        count += 1
+        print(f'Функция {func.__name__} вызывалась {count} раз')
+        return func(*args, **kwargs)
+    return inner
+
+
+def timer():
+    '''Сколько времени прошло с момента создания замыкания'''
+    start = perf_counter()
+    def inner():
+        return perf_counter() - start
+    return inner
+
+
+def create_dict():
+    key = 1
+    dct = {}
+    def inner(value):
+        nonlocal key
+        dct[key] = value
+        key += 1
+        return dct
+    return inner
+
+
+
 def my_func(a):
 def my_func(a):
     def inner(x):
     def inner(x):
         return x - a
         return x - a
@@ -59,6 +92,16 @@ def my_func(a):
 
 
 
 
 def main():
 def main():
+
+    f_1 = create_dict()
+    print(f_1('privet'))
+    print(f_1('poka'))
+    print(f_1([5, 2, 3]))
+
+    f2 = create_dict()
+    print(f2(5))
+    print(f2(15))
+
     # x = my_func(10)
     # x = my_func(10)
     # print(x(5))
     # print(x(5))
 
 
@@ -84,12 +127,12 @@ def main():
     # print(summator_1(5)) # печатает 106
     # print(summator_1(5)) # печатает 106
     # print(summator_1(2)) # печатает 108
     # print(summator_1(2)) # печатает 108
 
 
-    counter = count_calls()
-    counter()
-    counter()
-    print(counter.total_calls)
-    counter()
-    print(counter.total_calls)
+    # counter = count_calls()
+    # counter()
+    # counter()
+    # print(counter.total_calls)
+    # counter()
+    # print(counter.total_calls)
 
 
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':

+ 31 - 0
courses/python_func/decorator.py

@@ -0,0 +1,31 @@
+
+# Базовый синтаксис декоратора в python
+
+def my_decorator(func):
+
+    def wrapper_func():
+        # Делаем что-то до вызова функции
+        func()
+        # Делаем что-то после вызова функции
+
+    return wrapper_func
+
+
+def decorator(func):
+    def wrapper():
+        print('Start decorator')
+        func()
+        print('Finish decorator')
+    return wrapper
+
+
+@decorator
+def my_func():
+    print('This is my mega function!')
+
+def main():
+    my_func()
+
+
+if __name__ == '__main__':
+    main()