global關鍵字
如果函式內部試圖修改全域性變數,
python會自己遮蔽(shadowing)
>>> count = 5
>>> def myfun():
count = 10
print(10)
>>> myfun()
10>>> print(count)
5加入global關鍵字 宣告函式內的該變數是全域性變數
>>> def myfun():
global count
count = 10
print(10)
>>> myfun()
10>>> print(count)
10內嵌函式 :在函式中建立另乙個函式
>>> def fun1():
print("fun1()正在被呼叫...")
def fun2():
print("fun2()正在被呼叫")
fun2()
>>> fun1()
fun1()正在被呼叫...
fun2()正在被呼叫
執行fun1()後執行fun2()
def fun2():
print("fun2()正在被呼叫")
忽略,是給編譯器看的
內部函式的整個作用域都在外部函式之內
如果直接在外面寫fun2() 會報錯
閉包 函式正規化 函式式程式設計的重要語法結構
如果在乙個內部函式裡
函式式程式語言 lisp 用於cad繪圖 人工智慧
>>> def funx(x):
def funy(y):
return x*y
return funy #python中所有東西都是物件》可直接返回funy
>>> i = funx(8)
>>> i
.funy at 0x02e3d468>
>>> type(i)
# i是函式的函式
>>> i(5)
40>>> funx(8)(5)40
*不能在外部函式的外面對閉包進行呼叫
>>>funy(5) #報錯
*內部函式中,只能對外部函式訪問,不能修改
>>> def fun1():
x = 5
def fun2():
x *= x
return x
return fun2()
>>>fun1() 會報錯
呼叫fun1>>讀到return fun2() >> 作用 def fun2()
對fun2來說fun2外的是外部變數》 x=5會被遮蔽
>>> 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
課時20 內嵌函式和閉包
目錄 一 global關鍵字 二 內嵌函式 三 閉包 四 課時20課後習題及答案 一 global關鍵字 全域性變數的作用域是整個模組 整個 段 也就是 段內所有的函式內部都可以訪問到全域性變數。但是要注意一點,在函式內部僅僅去訪問全域性變數就好,不要試圖去修改它。因為那樣的話,python會使用遮...
內嵌函式和閉包
1 python裡面定義函式和c裡面一樣,也存在函式的巢狀定義,eg def fun1 x def fun2 y z x y return z return fun2則在函式呼叫的時候需要傳遞2個實參,分別給x,y 且形式為 result fun1 a b 2 由於在python函式定義的時候,出現...
python 內嵌函式和閉包
在函式體內定義函式 定義a 函式 defa print a 函式 定義b 函式 defb print b 函式 呼叫b 函式 b 呼叫a 函式 a 輸出 a 函式 b 函式 定義閉包函式 defa num1 def b num2 return num1 num2 return b 檢視a 函式的返回...