python几种装饰器的用法

mac2022-06-30  27

用函数装饰函数

这种比较常见首先定义装饰器函数

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

转载于:https://www.cnblogs.com/c-x-a/p/9710894.html

相关资源:Python装饰器使用你可能不知道的几种姿势
最新回复(0)