Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. # 2. Напишите параметризованный декоратор для классов, который будет считать и выводить время работы методов класса,
  2. # имена которых переданы в параметрах декоратора.
  3. # Пример:
  4. #   @time_methods('inspect', 'finalize')
  5. #   class Spam:
  6. #       def __init__(self, s):
  7. #           self.s = s
  8. #       def inspect(self):
  9. #            sleep(self.s)
  10. #       def foo(self):
  11. #            return self.s
  12. #
  13. #  a = Spam(2)
  14. #  a.inspect()  #  должно вывести сообщение о времени работы
  15. #  a.foo()  # ничего не выводить
  16. import time
  17.  
  18.  
  19. def time_methods(*args):
  20.     def inner_decorator(specific_class):
  21.         def wrapper(*other_args, **other_kwargs):
  22.             # if название передаваемого метода in args:
  23.                 t = time.perf_counter()
  24.                 # вызов метода, что передали
  25.                 print("Среднее время работы: {:.0f} мс.".format(time.perf_counter() - t * 1000))
  26.             return specific_class
  27.         return wrapper
  28.     return inner_decorator
  29.  
  30.  
  31. @time_methods('inspect', 'finalize')
  32. class Spam:
  33.     def __init__(self, s):
  34.         self.s = s
  35.  
  36.     def inspect(self):
  37.         time.sleep(self.s)
  38.  
  39.     def foo(self):
  40.         return self.s
  41.  
  42.  
  43. a = Spam(2)
  44. a.inspect()  # должно вывести сообщение о времени работы
  45. a.foo()  # ничего не выводить
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement