首页 > 编程语言 > 详细

python几种装饰器的用法

时间:2018-09-27 00:47:56      阅读:202      评论:0      收藏:0      [点我收藏+]

用函数装饰函数

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

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几种装饰器的用法

原文:https://www.cnblogs.com/c-x-a/p/9710894.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!