最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python基于locals返回作用域字典代码示例
时间:2020-10-17 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下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.
返回当前作用域内的局部变量和其值组成的字典
说明:
1. 函数功能返回当前作用域内的局部变量和其值组成的字典,与globals函数类似(返回全局变量)
>>> locals() {'__package__': None, '__loader__':, '__doc__': None, '__name__': '__main__', '__builtins__': , '__spec__': None} >>> a = 1 >>> locals() # 多了一个key为a值为1的项 {'__package__': None, '__loader__': , 'a': 1, '__doc__': None, '__name__': '__main__', '__builtins__': , '__spec__': None}
2. 可用于函数内。
>>> def f(): print('before define a ') print(locals()) #作用域内无变量 a = 1 print('after define a') print(locals()) #作用域内有一个a变量,值为1 >>> f>>> f() before define a {} after define a {'a': 1}
3. 返回的字典集合不能修改。
>>> def f(): print('before define a ') print(locals()) # 作用域内无变量 a = 1 print('after define a') print(locals()) # 作用域内有一个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 >>>
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27