# Python `locals()`函数
> 原文: [https://thepythonguru.com/python-builtin-functions/locals/](https://thepythonguru.com/python-builtin-functions/locals/)
* * *
于 2020 年 1 月 7 日更新
* * *
`locals()`函数返回一个字典,其中包含在本地名称空间中定义的变量。 在全局名称空间中调用`locals()`与调用[`globals()`](/python-builtin-functions/globals/)相同,并返回代表模块全局名称空间的字典。
其语法如下:
“`py
locals() -> dictionary containg local scope variables
“`
这是一个例子:
“`py
#!/usr/bin/python3
from pprint import pprint
a = 10
b = 20
def foo():
x = 30 # x and y are local variables
y = 40
print(“locals() = {0}”.format(locals()))
pprint(locals()) # same as calling globals()
print(‘*’ * 80)
print(“locals() == globals()? “, locals() == globals())
print(‘*’ * 80)
foo()
“`
**预期输出**:
“`py
{‘__builtins__’: ,
‘__cached__’: None,
‘__doc__’: None,
‘__file__’: ‘module1.py’,
‘__loader__’: <_frozen_importlib_external.sourcefileloader object at>,
‘__name__’: ‘__main__’,
‘__package__’: None,
‘__spec__’: None,
‘a’: 10,
‘b’: 20,
‘foo’: ,
‘pprint’: }
********************************************************************************
locals() == globals()? True
********************************************************************************
locals() = {‘y’: 40, ‘x’: 30}
“`
试试看:
“`py
from pprint import pprint
a = 10
b = 20
def foo():
x = 30 # x and y are local variables
y = 40
print(“locals() = {0}”.format(locals()))
pprint(locals()) # same as calling globals()
print(‘*’ * 80)
print(“locals() == globals()? “, locals() == globals())
print(‘*’ * 80)
foo()
“`
* * *
* * *
今天的文章python中locals函数_Python locals()函数分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/6532.html