日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python中locals函数_Python locals()函数

發布時間:2025/3/20 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。