python 装饰Python类中的每个方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 装饰Python类中的每个方法相关的知识,希望对你有一定的参考价值。

import time


def time_this(original_function):      
    print("decorating")
    def new_function(*args,**kwargs):
        print("starting timer")
        import datetime                 
        before = datetime.datetime.now()                     
        x = original_function(*args,**kwargs)                
        after = datetime.datetime.now()                      
        print(f"Elapsed Time = {after-before}")
        return x                                             
    return new_function  

def time_all_class_methods(Cls):
    class NewCls(object):
        def __init__(self,*args,**kwargs):
            self.oInstance = Cls(*args,**kwargs)
        def __getattribute__(self,s):
            """
            this is called whenever any attribute of a NewCls object is accessed. This function first tries to 
            get the attribute off NewCls. If it fails then it tries to fetch the attribute from self.oInstance (an
            instance of the decorated class). If it manages to fetch the attribute from self.oInstance, and 
            the attribute is an instance method then `time_this` is applied.
            """
            try:    
                x = super(NewCls,self).__getattribute__(s)
            except AttributeError:      
                pass
            else:
                return x
            x = self.oInstance.__getattribute__(s)
            if type(x) == type(self.__init__): # it is an instance method
                return time_this(x)                 # this is equivalent of just decorating the method with time_this
            else:
                return x
    return NewCls


@time_all_class_methods
class ImportantStuff:
    def __init__(self):
        print('initialized')
    def do_stuff_1(self):
        print('done')
    def do_stuff_2(self):
        pass
    def do_stuff_3(self):
        pass

x = ImportantStuff()
x.do_stuff_1()
x.do_stuff_2()
x.do_stuff_3()
def decorator(method):
    def wrapper(*args):
        print('pre method ', method.__name__)
        method(args)
        print('after method ', method.__name__)
    return wrapper

def do_decoration(klass):
    method_list = ['__init__']
    method_list = [func for func in dir(klass) if callable(getattr(klass, func)) and not func.startswith("__")]
    for method_s in method_list:
        print('decorate method:', method_s)
        method_f = getattr(klass, method_s)
        setattr(klass, method_s, decorator(method_f))
        # print(klass, method_s, method_f)

def class_decorator(original_class):
    do_decoration(original_class)
    return original_class

@class_decorator
class ImportantStuff:
    def __init__(self):
        print('initialized')
    def do_stuff_1(self):
        print('done')
    def do_stuff_2(self):
        pass
    def do_stuff_3(self):
        pass

x = ImportantStuff()
x.do_stuff_1()
x.do_stuff_2()
x.do_stuff_3()

以上是关于python 装饰Python类中的每个方法的主要内容,如果未能解决你的问题,请参考以下文章

Python 装饰器装饰类中的方法

Python 装饰器装饰类中的方法(转)

类中的Python装饰器

Python:如何使用父类中的方法装饰子类中的方法?

python中装饰器装饰类中的方法

python 装饰器调用其他类中的方法