時(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ì)了解一下。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ú)法輸出。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
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)
def func5(): b = 50 print(b) def func6(): nonlocal b # 非局部的,只適用于閉包內(nèi)部 b = 60 print(b) func6() print(b)func5()
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()
a = 123def func1(): print(a) print(b)func1() # 不能打印bb = 456func1() # 可以打印b
if True: a = 100print(a) for i in range(1, 10): print(i)print(i)
循環(huán)代碼塊中沒(méi)有作用域這樣的情況。關(guān)鍵詞:詳細(xì),講解,作用,函數(shù),命名,空間
客戶&案例
營(yíng)銷資訊
關(guān)于我們
客戶&案例
營(yíng)銷資訊
關(guān)于我們
微信公眾號(hào)
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。