脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 详解Python函数式编程之装饰器

详解Python函数式编程之装饰器

2022-10-20 11:37爱吃糖的范同学 Python

这篇文章主要为大家详细介绍了Python函数式编程之装饰器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

一、装饰器的本质:

装饰器(decorator)本质是函数闭包(function closure)的语法糖(Syntactic sugar)

函数闭包(function closure):

函数闭包是函数式语言(函数是一等公民,可作为变量使用)中的术语。函数闭包:一个函数,其参数和返回值都是函数,用于增强函数功能面向切面编程(AOP)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import time
# 控制台打印100以内的奇数:
def print_odd():
    for i in range(100):
        if i % 2 == 1:
            print(i)
# 函数闭包:用于增强函数func:给函数func增加统计时间的功能:
def count_time_wrapper(func):
    def improved_func():
        start_time = time.time()
        func()
        end_time = time.time()
        print(f"It takes {end_time - start_time} S to find all the odds in range !!!")
    return improved_func
if __name__ == '__main__':
    # 调用count_time_wrapper增强函数
    print_odd = count_time_wrapper(print_odd)
    print_odd()

闭包本质上是一个函数,闭包函数的传入参数和返回值都是函数,闭包函数得到返回值函数是对传入函数增强后的结果。

日志装饰器:

?
1
2
3
4
5
6
7
8
9
10
def log_wrapper(func):
    """
    闭包,用于增强函数func: 给func增加日志功能
    """
    def improved_func():
        start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 起始时间
        func()  # 执行函数
        end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 结束时间
        print("Logging: func:{} runs from {} to {}".format(func.__name__, start_time, end_time))
    return improved_func

二、装饰器使用方法:

通过装饰器进行函数增强,只是一种语法糖,本质上跟上个程序(使用函数闭包)完全一致。

详解Python函数式编程之装饰器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import time
# 函数闭包:用于增强函数func:给函数func增加统计时间的功能:
def count_time_wrapper(func):
    def improved_func():
        start_time = time.time()
        func()
        end_time = time.time()
        print(f"It takes {end_time - start_time} S to find all the odds in range !!!")
    return improved_func
# 控制台打印100以内的奇数:
@count_time_wrapper  # 添加装饰器
def print_odd():
    for i in range(100):
        if i % 2 == 1:
            print(i)
if __name__ == '__main__':
    # 使用  @装饰器(增强函数名) 给当前函数添加装饰器,等价于执行了下面这条语句:
    # print_odd = count_time_wrapper(print_odd)
    print_odd()

装饰器在第一次调用被装饰函数时进行增强,只增强一次,下次调用仍然是调用增强后的函数,不会重复执行增强!

保留函数参数和返回值的函数闭包:

  • 之前所写的函数闭包,在增强主要功能函数时,没有保留原主要功能函数的参数列表和返回值。
  • 一个保留参数列表和返回值的函数闭包写法:
?
1
2
3
4
5
6
7
def general_wrapper(func):
    def improved_func(*args, **kwargs):
        # 增强函数功能:
        ret = func(*args, **kwargs)
        # 增强函数功能:
        return ret
    return improved_func

优化装饰器(参数传递、设置返回值): 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import time
# 函数闭包:用于增强函数func:给函数func增加统计时间的功能:
def count_time_wrapper(func):
    # 增强函数:
    def improved_func(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"It takes {end_time - start_time} S to find all the odds in range !!!")
        # 原函数返回值
        return result
    return improved_func
# 计算0-lim奇数之和:
@count_time_wrapper
def count_odds(lim):
    cnt = 0
    for i in range(lim):
        if i % 2 == 1:
            cnt = cnt + i
    return cnt
if __name__ == '__main__':
    result = count_odds(10000000)
    print(f"计算结果为{result}!")

三、多个装饰器的执行顺序:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 装饰器1:
def wrapper1(func1):
    print("set func1"# 在wrapper1装饰函数时输出
    def improved_func1(*args, **kwargs):
        print("call func1"# 在wrapper1装饰过的函数被调用时输出
        func1(*args, **kwargs)
        return None
    return improved_func1
# 装饰器2:
def wrapper2(func2):
    print("set func2"# 在wrapper2装饰函数时输出
    def improved_func2(*args, **kwargs):
        print("call func1"# 在wrapper2装饰过的函数被调用时输出
        func2(*args, **kwargs)
        return None
    return improved_func2
@wrapper1
@wrapper2
def original_func():
    pass
if __name__ == '__main__':
    original_func()
    print("------------")
    original_func()

详解Python函数式编程之装饰器

这里得到的执行结果是,wrapper2装饰器先执行,原因是因为:程序从上往下执行,当运行到:

?
1
2
3
4
@wrapper1
@wrapper2
def original_func():
    pass

这段代码时,使用函数闭包的方式解析为:

?
1
original_func = wrapper1(wrapper2(original_func))

所以先进行wrapper2装饰,然后再对被wrapper2装饰完成的增强函数再由wrapper1进行装饰,返回最终的增强函数。

详解Python函数式编程之装饰器

四、创建带参数的装饰器:

装饰器允许传入参数,一个携带了参数的装饰器将有三层函数,如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import functools
def log_with_param(text):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            print('call %s():' % func.__name__)
            print('args = {}'.format(*args))
            print('log_param = {}'.format(text))
            return func(*args, **kwargs)
        return wrapper
    return decorator
@log_with_param("param!!!")
def test_with_param(p):
    print(test_with_param.__name__)
if __name__ == '__main__':
    test_with_param("test")

将其 @语法 去除,恢复函数调用的形式:

?
1
2
3
4
5
6
# 传入装饰器的参数,并接收返回的decorator函数
decorator = log_with_param("param!!!")
# 传入test_with_param函数
wrapper = decorator(test_with_param)
# 调用装饰器函数
wrapper("I'm a param")

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容! 

原文链接:https://blog.csdn.net/weixin_52058417/article/details/123203323

延伸 · 阅读

精彩推荐
  • Pythonpython中使用序列的方法

    python中使用序列的方法

    这篇文章主要介绍了python中使用序列的方法,较为详细的分析了Python序列的原理与使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    不是JS5232020-07-28
  • Pythonpython实战之制作表情包游戏

    python实战之制作表情包游戏

    想知道如何制作表情包游戏吗?用Python就可以搞定!本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...

    顾木子吖10772022-01-08
  • Pythonpython实现读Excel写入.txt的方法

    python实现读Excel写入.txt的方法

    下面小编就为大家分享一篇python实现读Excel写入.txt的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    momaojia11652021-02-07
  • Pythonpython Web应用程序测试selenium库使用用法详解

    python Web应用程序测试selenium库使用用法详解

    selenium主要是用来做自动化测试,支持多种浏览器,爬虫中主要用来解决JavaScript渲染问题本文详细介绍了在python中selenium模块的使用方法...

    脚本之家4532022-01-19
  • Pythonpython 请求服务器的实现代码(http请求和https请求)

    python 请求服务器的实现代码(http请求和https请求)

    本篇文章主要介绍了python 请求服务器的实现代码(http请求和https请求),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    可可_小虾米6222021-02-25
  • Pythonpython常见排序算法基础教程

    python常见排序算法基础教程

    这篇文章主要为大家详细介绍了python算法的基础教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    前程明亮1762020-09-29
  • Pythonpython commands模块的适用方式

    python commands模块的适用方式

    这篇文章主要介绍了python commands模块的适用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...

    以我丶之姓11672022-09-23
  • PythonPython使用MONGODB入门实例

    Python使用MONGODB入门实例

    这篇文章主要介绍了Python使用MONGODB的方法,实例分析了Python使用MONGODB的启动、安装及使用的相关技巧,需要的朋友可以参考下...

    蛇小狼3812020-06-27