python幾種裝飾器的用法
阿新 • • 發佈:2018-09-27
輸出 turn 定義 odin **kwargs add main file utf-8
用函數裝飾函數
這種比較常見首先定義裝飾器函數
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
python幾種裝飾器的用法