python中动态创建变量的探索 locals(), exec()

本文探讨了Python中动态变量的使用方法及其在不同作用域的表现。通过对比locals()和globals()函数,展示了局部作用域和全局作用域的区别,并通过示例说明了如何在局部作用域中动态创建变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近用到了python的动态变量. 遇到的问题和一些使用方法记录一下.

在全局作用域中, locals()和globals()代表同一个全局作用域字典变量, 因此在全局作用域使用locals()和globals()增加变量效果是一样的:

>>> if globals() == locals():
...     print 'yes'
... 
yes


>>> lc = locals()
>>> lc['hi'] = 'hello'
>>> hi
'hello'
>>> 

这个也没什么争议, 网上搜索很多, 问题就出在locals()做为函数或者类的局部作用域时:

>>> def test():
...     lc = locals()
...     lc['aa'] = 'world'
...     print aa
... 
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in test
NameError: global name 'aa' is not defined
>>> 

>>> def test1():
...     print locals()
...     lc = locals()
...     lc['aa'] = 'world'
...     print locals()
... 
>>> test1()
{}
{'aa': 'world', 'lc': {...}}aa' is not defined
>>> 

函数test() 报错为没有找到全局变量'aa', 而函数test1()可以看到使用locals()返回的字典变量可以给局部作用域添加变量,  所以网上说的locals()是只读的说法不正确, 另外一个证明locals()只读不正确的示例如下:

>>> def test():
...     lc = locals()
...     lc['bb'] = 'hello world'
...     print bb
... 
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in test
NameError: global name 'bb' is not defined

>>> def test1():
...     print locals()
...     lc = locals()
...     lc['bb'] = 'hello world'
...     exec("print bb")
... 
>>> test1()
{}
hello world

这里很明显, 使用exec()是可以找到这个通过locals()创建的局部变量, 这种方法在python35也是可以的.

转载于:https://my.oschina.net/nemesis/blog/751900

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值