Python基于locals返回作用域字典
英文文檔:
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.
返回當(dāng)前作用域內(nèi)的局部變量和其值組成的字典
說明:
1. 函數(shù)功能返回當(dāng)前作用域內(nèi)的局部變量和其值組成的字典,與globals函數(shù)類似(返回全局變量)
>>> locals(){’__package__’: None, ’__loader__’: <class ’_frozen_importlib.BuiltinImporter’>, ’__doc__’: None, ’__name__’: ’__main__’, ’__builtins__’: <module ’builtins’ (built-in)>, ’__spec__’: None}>>> a = 1>>> locals() # 多了一個key為a值為1的項{’__package__’: None, ’__loader__’: <class ’_frozen_importlib.BuiltinImporter’>, ’a’: 1, ’__doc__’: None, ’__name__’: ’__main__’, ’__builtins__’: <module ’builtins’ (built-in)>, ’__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<function f at 0x03D40588>>>> 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']: 1change locals valueb['a']: 2a is 1>>>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP基礎(chǔ)知識VBScript基本元素講解2. ASP.NET MVC使用jQuery ui的progressbar實現(xiàn)進(jìn)度條3. Python 合并拼接字符串的方法4. Linux刪除系統(tǒng)自帶版本Python過程詳解5. Python3 json模塊之編碼解碼方法講解6. python 使用事件對象asyncio.Event來同步協(xié)程的操作7. Python sublime安裝及配置過程詳解8. Python 利用Entrez庫篩選下載PubMed文獻(xiàn)摘要的示例9. Python 制作查詢商品歷史價格的小工具10. Python插件機(jī)制實現(xiàn)詳解

網(wǎng)公網(wǎng)安備