python locals()用法_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__’:, ‘__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>}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值