亚洲区国产区激情区无码区,国产成人mv视频在线观看,国产A毛片AAAAAA,亚洲精品国产首次亮相在线

Python 基礎(chǔ)教程

Python 流程控制

Python 函數(shù)

Python 數(shù)據(jù)類型

Python 文件操作

Python 對象和類

Python 日期和時(shí)間

Python 高級知識(shí)

Python 參考手冊

Python locals() 使用方法及示例

Python 內(nèi)置函數(shù)

locals()方法更新并返回當(dāng)前本地符號表的字典。

符號表是由編譯器維護(hù)的數(shù)據(jù)結(jié)構(gòu),其中包含有關(guān)程序的所有必要信息。

這些包括變量名,方法,類等。

符號表主要有兩種。

  1. 全局符號表

  2. 本地符號表

一個(gè)Global 符號表存儲(chǔ)與程序的全球范圍內(nèi)的所有信息,并使用Python在訪問globals()方法。

全局范圍包含所有函數(shù),與任何類或函數(shù)都沒有關(guān)聯(lián)的變量。

同樣,Local 符號表存儲(chǔ)與程序的本地范圍有關(guān)的所有信息,并使用locals()方法在Python中進(jìn)行訪問。

局部作用域可以在函數(shù)內(nèi),類內(nèi)等。 

推薦閱讀: Python的命名空間和范圍

locals()的語法

locals()方法的語法為:

locals()

locals()參數(shù)

locals()方法不帶任何參數(shù)。

locals()返回值

locals()方法更新并返回與當(dāng)前本地符號表關(guān)聯(lián)的字典。

示例1:locals()如何在Python中工作?

locals()

運(yùn)行該程序時(shí),輸出為:

{'In': ['', 'locals()'],
 'Out': {},
 '_': '',
 '__': '',
 '___': '',
 '__builtin__':,
 '__builtins__':,
 '__name__': '__main__',
 '_dh': ['/home/repl'],
 '_i': '',
 '_i1': 'locals()',
 '_ih': ['', 'locals()'],
 '_ii': '',
 '_iii': '',
 '_oh': {},
 '_sh':,
 'exit':,
 'get_ipython':>,
 'quit':}

注意:全局環(huán)境的globals()和locals()符號表是相同的。

示例2:locals()如何在本地范圍內(nèi)工作?

def localsNotPresent():
    return locals()

def localsPresent():
    present = True
    return locals()

print('localsNotPresent:', localsNotPresent())
print('localsPresent:', localsPresent())

運(yùn)行該程序時(shí),輸出為:

localsNotPresent: {}
localsPresent: {'present': True}

示例3:更新locals()字典值

def localsPresent():
    present = True
    print(present)
    locals()['present'] = False;
    print(present)

localsPresent()

運(yùn)行該程序時(shí),輸出為:

True
True

與globals()字典(它反映對實(shí)際全局表的更改)不同,locals()字典可能不會(huì)更改locals表中的信息。

Python 內(nèi)置函數(shù)