Skip to content

Instantly share code, notes, and snippets.

@tirinox
Last active April 28, 2023 00:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tirinox/507258b36e77dfec1448f8cf1d259356 to your computer and use it in GitHub Desktop.
Save tirinox/507258b36e77dfec1448f8cf1d259356 to your computer and use it in GitHub Desktop.
Декоратор класса. Для канала PyWay.
# copyright https://t.me/pyway
import time
# это вспомогательный декоратор будет декорировать каждый метод класса, см. ниже
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
delta = (te - ts) * 1000
print(f'{method.__name__} выполнялся {delta:2.2f} ms')
return result
return timed
def timeit_all_methods(cls):
class NewCls:
def __init__(self, *args, **kwargs):
# проксируем полностью создание класса
# как создали этот NewCls, также создадим и декорируемый класс
self._obj = cls(*args, **kwargs)
def __getattribute__(self, s):
try:
# папа, у меня есть атрибут s?
x = super().__getattribute__(s)
except AttributeError:
# нет сынок, это не твой атрибут
pass
else:
# да сынок, это твое
return x
# объект, значит у тебя должен быть атрибут s
attr = self._obj.__getattribute__(s)
# метод ли он?
if isinstance(attr, type(self.__init__)):
# да, обернуть его в измеритель времени
return timeit(attr)
else:
# не метод, что-то другое
return attr
return NewCls
@timeit_all_methods
class Foo:
def a(self):
print("медленный метод начался")
time.sleep(1.0)
print("медленный метод кончился")
f = Foo()
f.a()
# медленный метод начался
# медленный метод кончился
# a выполнялся 1000.17 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment