装饰器--python


python装饰器回顾

返回函数

什么是装饰器

python装饰器就是用于拓展原来函数功能的一种函数,目的是在不改变原函数定义的情况下,给函数增加新的功能。
这个函数的特殊之处在于它的返回值也是一个函数,这个函数是内嵌“原”函数的函数

在代码运行期间动态的增加功能
装饰器(decorator)是修改其它函数功能的函数,是返回函数的高阶函数

demo

# -*- coding: utf-8 -*-

'''
- 这是一个decorator
- 使用一个函数作为参数
- 它返回一个函数
'''
def a_new_decorator(a_func):    
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")
    return wrapTheFunction


'''
- 使用a_new_decorator装饰a_function_requiring_decoration
- @a_new_decorator 等价于 a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
'''
@a_new_decorator
def a_function_requiring_decoration():

    print("I am the function which needs some decoration remove my foul smell")

a_function_requiring_decoration()

运行结果
FIyq7F.png

@a_new_decorator 等价于 a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

** 下面这段程序和上面那段等价 **

# -*- coding: utf-8 -*-

def a_new_decorator(a_func):

    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")

        a_func()

        print("I am doing some boring work after executing a_func()")

    return wrapTheFunction

def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell")

#a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"

a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()

a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()

应用:日志打印

在wrap函数内,首先打印日志,再调用原始函数
*args表示任何多个无名参数,它是一个tuple;**kwargs表示关键字参数,它是一个dict

PS

对于上面的demo

>>>print(a_function_requiring_decoration.__name__)
#输出结果为
wrapTheFunction

明显不是我们想要的,我们函数的名字和注释文档被重写了
预期应该为
a_function_requiring_decoration

使用functools.warps可以解决这个问题

上面的demo应该这样写

参考


文章作者: ShanSan
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 ShanSan !
 上一篇
泛型算法-1 泛型算法-1
泛型算法-1 泛型算法实现了一些经典算法的公共接口,如排序和搜索;称它们是“泛型的”,是因为它们可以用于不同类型的元素的和多种容器类型(不仅包括标准库类型,还包括内置的数组类型),以及其它类型的序列。 ** 大多数算法都定义在头文件alg
2019-01-03
下一篇 
博客搭建参考汇总 博客搭建参考汇总
以下是我搭建博客参考的一些教程 hexo博客搭建教程https://blog.csdn.net/gdutxiaoxu/article/details/53576018 https://m.w3cschool.cn/hexo_blog/h
2019-01-01
  目录