Python闭包和装饰器原理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Python闭包和装饰器
 
############# 闭包 ##############
'''
    1. 一个外层函数,内嵌一个内层函数;
    2. 内层函数使用外层函数的参数;
    3. 外层函数将内层函数作为返回值返回
'''
 
# 外层函数
def outer(msg):
    # 内层函数
    def inner():
        # 内层函数使用外层函数的参数
        print(msg)
    # 将内层函数作为返回值返回
    return inner
 
inner = outer('hello world')
inner()    # 结果打印:hello world
 
# 在这个过程中,调用完outer()之后,将变量msg保留了下来,在inner()调用时可以继续使用
 
 
############# 装饰器 ##############
'''
    1. 装饰器的本质就是闭包,只不过外层函数的参数就是 “要装饰的那个函数”;
'''
 
# 定义一个装饰器decoration
def decoration(func):
 
    def inner():
        # 在前面添加新的功能
        print('before new function!')
 
        # 调用原本的函数
        func()
 
        # 在后面添加新的功能
        print('after new function!')
 
    return inner
 
# 定义函数hello
def hello():
    print('hello')
 
# 用装饰器decoration装饰函数hello
hello = decoration(hello)
hello()
'''
    结果打印:
    before new function!
    hello
    after new function!
'''
 
# 用装饰器decoration来装饰函数的另一种写法,效果是一样的
@decoration
def hello_2():
    print('hello_2')
 
hello_2()
'''
    结果打印:
    before new function!
    hello_2
    after new function!
'''

  

posted @   映辉  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2023-05-27 django设置中文和上海时间
点击右上角即可分享
微信分享提示