1. 程式人生 > >Python自學之函數內嵌和閉包

Python自學之函數內嵌和閉包

sign back cdc error: lisp 編程語言 enc lin sig

函數內嵌指一個函數內部包含定義另一個函數
舉例:

>> def fun1():
print(‘fun1()正在被調用...‘)
def fun2():
print(‘fun2()正在被調用...‘)
fun2()

>> fun1()
fun1()正在被調用...
fun2()正在被調用...
>> fun2()
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
fun2()
NameError: name ‘fun2‘ is not defined

閉包(closure)是函數式編程的一個重要的語法結構,函數式編程是一種編程範式,著名的函數式編程語言就是LISP語言.
Python中的閉包從表現形式上定義為:如果在一個內部函數裏,對在外部作用域(但不是在全局作用域)的變量進行引用,那麽內部函數就是被認為閉包.
舉例

>> def FunX(x):
def FunY(y): //FunY就是FunX的內部函數,FunX的整個函數作用域為FunY的外部作用域,變量x
return x * y
return FunY

>> i = FunX(8)
>> i //i是一個function

<function FunX.<locals>.FunY at 0x029CDCD8>
>> type(i)
<class ‘function‘>
>> i(5)
40
>> FunX(8)(5)
40
>> FunY(5)
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
FunY(5)
NameError: name ‘FunY‘ is not defined

內部函數對外部函數的局部變量只能進行引用,不能進行修改

舉例:

>> def Fun1():
x = 5
def Fun2():
x *= x //x為外部函數的局部變量,只能引用不能修改
return x
return Fun2()

>> Fun1()
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
Fun1()
File "<pyshell#38>", line 6, in Fun1
return Fun2()
File "<pyshell#38>", line 4, in Fun2
x *= x
UnboundLocalError: local variable ‘x‘ referenced before assignment
>>

解決辦法
方法一:
容器類型存放解決,容器類型不是存放在棧中

>> def Fun1():
x = [5] //用列表來存放x
def Fun2():
x[0] *= x[0]
return x[0]
return Fun2()

>> Fun1()
25
>>
方法二
nonlocal關鍵字,3.0以後版本加入
>> def Fun1():
x = 5
def Fun2():
nonlocal x
x *= x
return x
return Fun2()

>> Fun1()
25
>>

Python自學之函數內嵌和閉包