當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python locals()用法及代碼示例


locals()Python中的function返回當前本地符號表的字典。

符號表:它是由編譯器創建的數據結構,用於存儲執行程序所需的所有信息。
本地符號表:該符號表存儲了程序本地範圍所需的所有信息,並且可以使用python內置函數來訪問此信息locals()

用法: locals()

參數:此函數不接受任何輸入參數。

返回類型:這將返回存儲在本地符號表中的信息。

範例1:

# Python program to understand about locals 
  
# here no local variable is present 
def demo1():
    print("Here no local variable  is present:", locals()) 
      
# here local variables are present 
def demo2():
     name = "Ankit"
     print("Here local variables are present:", locals()) 
       
# driver code 
demo1() 
demo2()
輸出:
Here no local variable  is present: {}
Here local variables are present: {'name':'Ankit'}


範例2:使用更新locals()

與globals()不同,此函數無法修改本地符號表的數據。下麵的程序清楚地說明了這一點。

# Python program to understand about locals 
  
# here no local varible is present 
def demo1():
    print("Here no local variable  is present:", locals()) 
      
# here local variables are present 
def demo2():
     name = "Ankit"
     print("Here local variables are present:", locals()) 
     print("Before updating name is :", name) 
       
     # trying to change name value 
     locals()['name'] = "Sri Ram"
       
     print("after updating name is:", name) 
       
# driver code 
demo1() 
demo2()
輸出:
Here no local variable  is present: {}
Here local variables are present: {'name':'Ankit'}
Before updating name is : Ankit
after updating name is: Ankit

範例3: locals() 為全局環境。

在全局環境下,本地符號表與全局符號表相同。

# Python program to understand about locals 
  
# data using locals 
print("This is using locals():", locals()) 
  
# data using globals 
print("This is using globals():", globals())
輸出:

This is using locals():{‘__file__’:‘/home/34dde64e1e47944021cdf478b97f13a0.py’, ‘__doc__’:None, ‘__name__’:‘__main__’, ‘__cached__’:None, ‘__spec__’:None, ‘__builtins__’:<module ‘builtins’ (built-in)>, ‘__package__’:None, ‘__loader__’:%lt;_frozen_importlib_external.SourceFileLoader object at 0x7f885e463470>}
This is using globals():{‘__file__’:‘/home/34dde64e1e47944021cdf478b97f13a0.py’, ‘__doc__’:None, ‘__name__’:‘__main__’, ‘__cached__’:None, ‘__spec__’:None, ‘__builtins__’:<module ‘builtins’ (built-in)>, ‘__package__’:None, ‘__loader__’:<_frozen_importlib_external.SourceFileLoader object at 0x7f885e463470>}



相關用法


注:本文由純淨天空篩選整理自ankit15697大神的英文原創作品 Python | locals() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。