Декоратор класса. Для канала PyWay.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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