import time
import math
from functools import wraps
class Decorator(object):
def __init__(self, func):
self.f = func
def __call__(self, *args, **kwargs):
start_time = time.time()
result = self.f(*args, **kwargs)
print(time.time() - start_time)
return result
def profiling_wrapper(f):
@wraps(f)
def wrapper(*args, **kwargs):
start_time = time.time()
result = f(*args, **kwargs)
print("[func_name]: ", f.__name__+'\n' + "[use_time]: ", time.time() - start_time)
return result
return wrapper
def profiling_all_class_methods(Cls):
"""装饰类中所有方法"""
class ProfiledClass(object):
def __init__(self, *args, **kwargs):
self.inst = Cls(*args, **kwargs)
def __getattribute__(self, item):
try:
x = super(ProfiledClass, self).__getattribute__(item)
except AttributeError:
pass
else:
x = self.inst.__getattribute__(item)
if isinstance(x, self.__init__):
return profiling_wrapper(x)
else:
return x
return ProfiledClass
@profiling_all_class_methods
class DoMathStuff(object):
def __init__(self):
self.fib()
self.logarithm()
def fib(self):
a, b = 0, 1
for i in range(10000 + 1):
a, b = b, a + b
return a
@profiling_wrapper
def logarithm(self):
i = 1
for i in range(1, 1000000):
math.log(i)
i += 1
if __name__ == '__main__':
DoMathStuff()
Python设计模式--装饰器模式
最新推荐文章于 2024-06-14 09:50:01 发布