locals()
Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.
說明:
1. 函數(shù)功能返回當(dāng)前作用域內(nèi)的局部變量和其值組成的字典,與globals函數(shù)類似(返回全局變量)
>>> locals() {'__package__': None, '__loader__':, '__doc__': None, '__name__': '__main__', '__builtins__': , '__spec__': None} >>> a = 1 >>> locals() # 多了一個key為a值為1的項(xiàng) {'__package__': None, '__loader__': , 'a': 1, '__doc__': None, '__name__': '__main__', '__builtins__': , '__spec__': None}
2. 可用于函數(shù)內(nèi)。
>>> def f(): print('before define a ') print(locals()) #作用域內(nèi)無變量 a = 1 print('after define a') print(locals()) #作用域內(nèi)有一個a變量,值為1 >>> f>>> f() before define a {} after define a {'a': 1}
3. 返回的字典集合不能修改。
>>> def f(): print('before define a ') print(locals()) # 作用域內(nèi)無變量 a = 1 print('after define a') print(locals()) # 作用域內(nèi)有一個a變量,值為1 b = locals() print('b["a"]: ',b['a']) b['a'] = 2 # 修改b['a']值 print('change locals value') print('b["a"]: ',b['a']) print('a is ',a) # a的值未變 >>> f() before define a {} after define a {'a': 1} b["a"]: 1 change locals value b["a"]: 2 a is 1 >>>
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com