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__’:, ‘__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__’:, ‘__package__’:None, ‘__loader__’:<_frozen_importlib_external.sourcefileloader object at>}