Advertisement
Guest User

python_dec

a guest
Jun 18th, 2021
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. from datetime import datetime
  2. import time
  3. from typing import Callable
  4. import functools
  5.  
  6.  
  7. def log_method(time_format: str, cls_name: str) -> Callable:
  8. """ Декоратор. Выводит имена класса, метода, время запуска и время его работы."""
  9.  
  10. def method_decorator(func: Callable) -> Callable:
  11. @functools.wraps(func)
  12. def wrapped_func(*args, **kwargs):
  13. formatted_time = ''.join('%' + sbl if sbl.isalpha() else sbl for sbl in time_format)
  14. print('- Запускается {}.{}. Дата и время запуска: {}'
  15. .format(cls_name, func.__name__, datetime.now().strftime(formatted_time)))
  16. start = time.time()
  17. result = func(*args, **kwargs)
  18. end = time.time()
  19. print('- Завершение {}.{}, время работы = {}s'
  20. .format(cls_name, func.__name__, round(end - start, 3)))
  21. return result
  22. return wrapped_func
  23. return method_decorator
  24.  
  25.  
  26. def log_methods(time_format: str) -> Callable:
  27. """ Декоратор. Применяет декоратор log_method ко всем методам класса. """
  28.  
  29. def wrapped(cls):
  30. for i_method in dir(cls):
  31. if i_method.endswith('__') is False:
  32. method = getattr(cls, i_method)
  33. if callable(method):
  34. decorated_method = log_method(time_format, cls.__name__)(method)
  35. setattr(cls, i_method, decorated_method)
  36. return cls
  37. return wrapped
  38.  
  39.  
  40. if __name__ == '__main__':
  41.  
  42. @log_methods("b d Y - H:M:S")
  43. class ExampleClass:
  44. @classmethod
  45. def sum_1(cls) -> int:
  46. print("sum 1")
  47. number = 100
  48. result = 0
  49. for _ in range(number + 1):
  50. result += sum([i_num ** 2 for i_num in range(10000)])
  51. return result
  52.  
  53. def sum_2(self):
  54. print("sum 2")
  55. number = 200
  56. result = 0
  57. for _ in range(number + 1):
  58. result += sum([i_num ** 2 for i_num in range(10000)])
  59. return result
  60.  
  61.  
  62. my_obj = ExampleClass()
  63. my_obj.sum_1()
  64. my_obj.sum_2()
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement