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>}
相关用法
- Python now()用法及代码示例
- Python cmp()用法及代码示例
- Python map()用法及代码示例
- Python ord()用法及代码示例
- Python int()用法及代码示例
- Python dir()用法及代码示例
- Python hex()用法及代码示例
- Python sum()用法及代码示例
- Python id()用法及代码示例
- Python tell()用法及代码示例
- Python oct()用法及代码示例
注:本文由纯净天空筛选整理自ankit15697大神的英文原创作品 Python | locals() function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。