python用類實現裝飾器


一般實現python裝飾器都是采用方法的模式,看起來有點復雜,模式如下:

def send_msg_simple(url):
    def decorator(func):
        def wrapper(*args, **kw):
            func(*args, **kw)
            group_robot(url, "完畢:%s.%s" % (kw['db'], kw['table']))

        return wrapper

    return decorator

 

但其實也可以采用類的方式,看起來邏輯更為清晰:

class DecoratorTest(object): #定義一個類
    def __init__(self,func):
        self.__func = func
    def __call__(self):  #定義call方法,當直接調用類的時候,運行這里。
        print('pre msg')
        self.__func()    
        print('post msg')


@DecoratorTest  
def test():
    print('主函數體')


if __name__=='__main__':
    test() 

 下面是cookbook上的類裝飾器實現,略有不同

# 為了將裝飾器定義成一個類,你需要確保它實現了 __call__() 和 __get__() 方 法。
# 例如,下面的代碼定義了一個類,它在其他函數上放置一個簡單的記錄層:
import types
from functools import wraps

class Profiled:
    def __init__(self, func):
        wraps(func)(self)
        self.ncalls = 0
    def __call__(self, *args, **kwargs): 
        self.ncalls += 1
        return self.__wrapped__(*args, **kwargs)
    def __get__(self, instance, cls): 
        if instance is None:
            return self 
        else:
            return types.MethodType(self, instance)

# 你可以將它當做一個普通的裝飾器來使用,在類里面或外面都可以:
@Profiled
def add(x, y): 
    return x + y

class Spam: 
    @Profiled
    def bar(self, x): 
        print(self, x)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM