python装饰器有几种_python几种装饰器的用法
用函數裝飾函數
這種比較常見首先定義裝飾器函數
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>,)-{})
calculated
7
add-(<__main__.funcdemo object at>,)-{})
cache
7
總結
以上是生活随笔為你收集整理的python装饰器有几种_python几种装饰器的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql怎么禁止远程连接_mysql禁
- 下一篇: nginx +php + redis和