>>> def fun1():
print('fun1正在被調用···')
def fun2():
print('fun2正在被調用···')
fun2()
>>> fun1()
fun1正在被調用···
fun2正在被調用···
>>> fun2()
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
fun2()
NameError: name 'fun2' is not defined
閉包需要滿足以下三個條件:
①存在於嵌套關係的函數中
②嵌套的內部函數引用了外部函數的變量
③嵌套的外部函數會將內部函數名作爲返回值返回
>>> def outer(start=0):
count = [start]
def inner():
count[0] += 1
return count[0]
return inner
>>> out = outer(5)
>>> print(out())
6
>>> def funx(x):
def funy(y):
return x*y
return funy
>>> i = funx(8)
>>> i
<function funx.<locals>.funy at 0x00000232BDFFC840>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> funx(8)(5)
40
例三
>>> def fun1():
x = 5
def fun2():
x *=x
return x
return fun2()
>>> fun1()
Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
fun1()
File "<pyshell#59>", line 6, in fun1
return fun2()
File "<pyshell#59>", line 4, in fun2
x *=x
UnboundLocalError: local variable 'x' referenced before assignment
#運行至return fun2(),內部函數試圖修改全局變量(相對而言),Python用shadowing隱藏全局變量(相對而言),即在內部函數fun2()的外部空間中的x = 5被屏蔽,故x未被賦值
例三
>>> 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
>>>