File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
blog/2022-12-14-python-notes Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change @@ -49,6 +49,58 @@ date: 2023-01-07 17:50
4949
5050yield from + 可迭代对象,实现对可迭代对象的再一次yield
5151
52+ ### 闭包
53+ > 外部函数中定义了一个内部函数,返回了内部函数的引用,内部函数引用了外部函数的变量
54+
55+ 自由变量:
56+ > 在当前作用域中引用了但未定义的变量,而是在外部作用域中定义的,如果要访问外部作用域中的非全局变量,需用关键字nonlocal定义
57+
58+ 示例:
59+ ``` python
60+ # 因访问了外部作用域中的非全局变量,会报错:UnboundLocalError: local variable 'a' referenced before assignment
61+ def outer ():
62+ a = 0
63+ def inner (y ):
64+ a += y
65+ return a
66+ return inner
67+
68+
69+ # 使用nonlocal定义自由变量
70+ def outer ():
71+ a = 0
72+ def inner (y ):
73+ nonlocal a
74+ a += y
75+ return a
76+ return inner
77+
78+ func = outer()
79+ func(1 )
80+ func(2 )
81+ >> > output: 3
82+
83+
84+ # 如果外部变量是可变对象,内部函数可以直接通过引用修改该对象的内容,这种行为并不需要额外的 global 或 nonlocal 关键字
85+ def outer ():
86+ a = []
87+ def inner (y ):
88+ a.append(y)
89+ return a
90+ return inner
91+
92+ func = outer()
93+ func(1 )
94+ func(2 )
95+ >> > output: [1 , 2 ]
96+ ```
97+
98+
99+ 闭包的作用:
100+ 1 . 封装和隐藏数据:通过闭包,内嵌函数可以访问外部函数的变量,而外部环境无法直接修改这些变量,从而实现了封装,保护数据不被外部直接访问。
101+ 2 . 延迟执行:闭包常用于回调函数或延迟执行的场景,确保函数在某个时刻可以访问到当时的变量状态。
102+ 3 . 维持状态:闭包允许我们在函数中“记住”状态,比如计数器、缓存等。
103+
52104
53105
54106### 类与对象
You can’t perform that action at this time.
0 commit comments