Python--12 内嵌函数和闭包
內嵌函數/內部函數
>>> def fun1():
... print('fun1()正在調用')
... def fun2():
... print('fun2()正在被調用')
... fun2()
...
>>> fun1()
fun1()正在調用
fun2()正在被調用
內部函數作用域在外部函數之內
>>> fun2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'fun2' is not defined
閉包?closure
閉包函數式編程的一種重要語法結構??
函數式編程是一種編程范式,對代碼進行抽象提煉和概括,使代碼重用性變高
python閉包在表現形式表現為 如果在一個內部函數里對外部作用域(但不是全局作用域)的變量進行引用,內部函數就被認為是閉包?
>>> def FunX(x):
... def FunY(y):
... return x * y
... return FunY
...
>>> i = FunX(8)
>>> i
<function FunX.<locals>.FunY at 0x7f5f41b05b70>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> FunX(8)(5)
40
>>> FunY(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'FunY' is not defined
?
?
>>> def Fun1():
... x=5
... def Fun2():
... x *= x
... return x
... return Fun2()
...
>>> Fun1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in Fun1
File "<stdin>", line 4, in Fun2
UnboundLocalError: local variable 'x' referenced before assignment
列表沒有存放在棧里
>>> def Fun1():
... x = [5]
... def Fun2():
... x[0] *= x[0]
... return x[0]
... return Fun2()
...
>>> Fun1()
25
nonlocal 關鍵字
>>> def Fun1():
... x=5
... def Fun2():
... nonlocal x
... x *= x
... return x
... return Fun2()
...
>>> Fun1()
25
?
轉載于:https://www.cnblogs.com/fengjunjie-w/p/7491109.html
總結
以上是生活随笔為你收集整理的Python--12 内嵌函数和闭包的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Dropwizard入门及开发步骤
- 下一篇: python初步学习-查看文档及数据类型