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 0x036D4F50>,)-{})
calculated
7
add-(<__main__.FuncDemo object at 0x036D4F50>,)-{})
cache
7
复制代码


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值