python装饰器的使用

Posted 三体

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python装饰器的使用相关的知识,希望对你有一定的参考价值。

借用装饰器,我们可以批量的对老的函数进行改造或扩展老函数功能,比如需要对函数的接收参数进行过滤,Flash的url路由功能就是使用的这个方式

def dropoushu():  # 这一层函数可以去掉,如果去掉了,则使用@checkjiou这种方式调用该装饰器
    def checkjiou(func):
        def wrapper(*args):
            tmp_list = args[0]
            result_list = [i for i in tmp_list if i%2 ==0]  # 对calculate函数的入参list中的奇数过滤掉
            return func(*tuple([result_list]))  # result_list=[0, 2, 4, 6]
        return wrapper
    return checkjiou

@dropoushu()
def calculate(a_list):
    print a_list  # [0, 2, 4, 6]

if __name__ == "__main__":
    calculate([i for i in range(7)])  # 此处的数据应该是[0, 1, 2, 3, 4, 5, 6]

 

以上是关于python装饰器的使用的主要内容,如果未能解决你的问题,请参考以下文章

python 装饰器的使用

python 函数 装饰器的使用方法

python使用上下文对代码片段进行计时,非装饰器

Python装饰器的实现和万能装饰器

转发对python装饰器的理解

python 多个装饰器的调用顺序