Python--12 内嵌函数和闭包
內(nèi)嵌函數(shù)/內(nèi)部函數(shù)
>>> def fun1():
... print('fun1()正在調(diào)用')
... def fun2():
... print('fun2()正在被調(diào)用')
... fun2()
...
>>> fun1()
fun1()正在調(diào)用
fun2()正在被調(diào)用
內(nèi)部函數(shù)作用域在外部函數(shù)之內(nèi)
>>> fun2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'fun2' is not defined
閉包?closure
閉包函數(shù)式編程的一種重要語法結(jié)構(gòu)??
函數(shù)式編程是一種編程范式,對代碼進(jìn)行抽象提煉和概括,使代碼重用性變高
python閉包在表現(xiàn)形式表現(xiàn)為 如果在一個內(nèi)部函數(shù)里對外部作用域(但不是全局作用域)的變量進(jìn)行引用,內(nèi)部函數(shù)就被認(rèn)為是閉包?
>>> 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 關(guān)鍵字
>>> def Fun1():
... x=5
... def Fun2():
... nonlocal x
... x *= x
... return x
... return Fun2()
...
>>> Fun1()
25
?
轉(zhuǎn)載于:https://www.cnblogs.com/fengjunjie-w/p/7491109.html
總結(jié)
以上是生活随笔為你收集整理的Python--12 内嵌函数和闭包的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Dropwizard入门及开发步骤
- 下一篇: java--杨辉三角