python中locals函数_Python locals()函数
# 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()函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 同一事务多次加for_谈谈事务隔离级别,
- 下一篇: jsch设置代理_Java使用JSch组