国产成人精品无码青草_亚洲国产美女精品久久久久∴_欧美人与鲁交大毛片免费_国产果冻豆传媒麻婆精东

15158846557 在線咨詢 在線咨詢
15158846557 在線咨詢
所在位置: 首頁(yè) > 營(yíng)銷資訊 > 網(wǎng)站運(yùn)營(yíng) > Python函數(shù)命名空間和作用域(Local,Global) 【詳細(xì)講解】

Python函數(shù)命名空間和作用域(Local,Global) 【詳細(xì)講解】

時(shí)間:2023-05-08 04:39:01 | 來(lái)源:網(wǎng)站運(yùn)營(yíng)

時(shí)間:2023-05-08 04:39:01 來(lái)源:網(wǎng)站運(yùn)營(yíng)

Python函數(shù)命名空間和作用域(Local,Global) 【詳細(xì)講解】:Python函數(shù)是一個(gè)包裝起來(lái)的代碼塊,通過(guò)前面的返回函數(shù),閉包函數(shù)等課程,我們發(fā)現(xiàn)其內(nèi)部變量定義在不同的位置,使用起來(lái)的效果就有所不同,這就是python函數(shù)的作用域和命名空間。下面通過(guò)代碼來(lái)詳細(xì)了解一下。

1.Local作用域

a = 100def func5(): b = 50 a = 99print('函數(shù)內(nèi)a', a)print('函數(shù)內(nèi)b', b) print('函數(shù)外a', a)func5()print('函數(shù)外b', b)返回結(jié)果:

函數(shù)外a 100函數(shù)內(nèi)a 99函數(shù)內(nèi)b 50Traceback (most recent call last): File "C:/Users/Administrator/Desktop/python知識(shí)總結(jié)/2.python自學(xué)網(wǎng)-通用模塊-視頻源碼/test.py", line 12, in <module> print('函數(shù)外b', b)NameError: name 'b' is not defined上面函數(shù)中定義b變量,所以外面無(wú)法輸出。

2.Enclosing function locals作用域

a = 100def func5(): b = 50 print('函數(shù)內(nèi)a', a) print('函數(shù)內(nèi)b', b) def func6(): print('下層函數(shù)內(nèi)a', a) print('下層函數(shù)內(nèi)b', b) func6()func5()返回結(jié)果:

函數(shù)內(nèi)a 100函數(shù)內(nèi)b 50下層函數(shù)內(nèi)a 100下層函數(shù)內(nèi)b 50

3.Global全局變量

a = 123def func(): a = 100print(a)print(a)func()print(a) a = 123def func(): global a # 這里不能使用nonlocal a = 100 print(a) print(locals()) # 查看局部變量 print(globals()) # 查看全局變量print(a)func()print(a)

4.非局部變量nonlocal

def func5(): b = 50 print(b) def func6(): nonlocal b # 非局部的,只適用于閉包內(nèi)部 b = 60 print(b) func6() print(b)func5()

5.就近原則

b = 1111def func5(): b = 50 print(b) def func6(): b = 60 print(b) # 這里的b從內(nèi)到外究竟查找 func6() print(b)func5()a = 100def func5(): b = 50 print(a) print(b) def func6(): b = 60 print(b) print(a)func5()

6.函數(shù)執(zhí)行順序

a = 123def func1(): print(a) print(b)func1() # 不能打印bb = 456func1() # 可以打印b

7.循環(huán)、判斷代碼塊中作用域問(wèn)題

if True: a = 100print(a) for i in range(1, 10): print(i)print(i)循環(huán)代碼塊中沒(méi)有作用域這樣的情況。

關(guān)鍵詞:詳細(xì),講解,作用,函數(shù),命名,空間

74
73
25
news

版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。

為了最佳展示效果,本站不支持IE9及以下版本的瀏覽器,建議您使用谷歌Chrome瀏覽器。 點(diǎn)擊下載Chrome瀏覽器
關(guān)閉