python幾種裝飾器的用法

公號_python學習開發發表於2018-10-16

用函式裝飾函式

這種比較常見首先定義裝飾器函式

def cache(func):
    data = {}
    @wraps(func)
    def wrapper(*args, **kwargs):
        key = f'{func.__name__}-{str(args)}-{str(kwargs)})'
        if key in data:
            result = data.get(key)
            print('cache')
        else:
            result = func(*args, **kwargs)
            data[key] = result
            print('calculated')
        return result
    return wrapper
複製程式碼

然後定義一個需要裝飾的函式

@cache
def add(a, b):
    return a + b
複製程式碼

呼叫add。

print(add(2, 4))
print(add(2, 4))
複製程式碼

輸出

add-(2, 4)-{})
calculated
6
add-(2, 4)-{})
cache
6
複製程式碼

用類裝飾函式

# -*- coding: utf-8 -*-
# @Time : 2018/9/26 23:30
# @Author : cxa
# @File : cache.py
# @Software: PyCharm

class Cache:
    def __init__(self, func):
        self.data = {}
        self.func = func

    def __call__(self, *args, **kwargs):
        key = f'{self.func.__name__}-{str(args)}-{str(kwargs)})'
        print(key)
        data = self.data
        if key in data:
            result = data.get(key)
            print('cache')
        else:
            result = self.func(*args, **kwargs)
            data[key] = result
            print('calculated')
        return result
複製程式碼

然後定義一個需要裝飾的函式

@Cache
def add(a, b):
    return a + b
複製程式碼

呼叫add。

print(add(2, 4))
print(add(2, 4))
複製程式碼

輸出

add-(2, 4)-{})
calculated
6
add-(2, 4)-{})
cache
6
複製程式碼

類裝飾類的方法

一個裝飾器類

# -*- coding: utf-8 -*-
# @Time : 2018/9/26 23:30
# @Author : cxa
# @File : cache.py
# @Software: PyCharm

class Cache:
    def __init__(self, func):
        self.data = {}
        self.func = func

    def __call__(self, *args, **kwargs):
        key = f'{self.func.__name__}-{str(args)}-{str(kwargs)})'
        print(key)
        data = self.data
        if key in data:
            result = data.get(key)
            print('cache')
        else:
            result = self.func(*args, **kwargs)
            data[key] = result
            print('calculated')
        return result
複製程式碼

然後定義一個需要裝飾的類,裝飾add方法

class FuncDemo():
    def __init__(self,w,h):
        self.w=w
        self.h=h

    @property
    @Cache
    def add(self):
        return self.w+self.h
複製程式碼

呼叫並輸出

add-(<__main__.FuncDemo object at 0x036D4F50>,)-{})
calculated
7
add-(<__main__.FuncDemo object at 0x036D4F50>,)-{})
cache
7
複製程式碼


相關文章