Python设计模式--装饰器模式

纵然是瞬间 提交于 2019-12-25 03:16:09
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()


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!