下面的代码给出了不同的输出
Python2
并在
Python3
:
from sys import version
print(version)
def execute(a, st):
b = 42
exec("b = {}\nprint('b:', b)".format(st))
print(b)
a = 1.
execute(a, "1.E6*a")
蟒蛇2
印刷品:
2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
('b:', 1000000.0)
1000000.0
蟒蛇3
印刷品:
3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]
b: 1000000.0
42
为什么?
蟒蛇2
绑定变量
b
在
execute
函数的字符串中的值
exec
函数,而
蟒蛇3
不是这样吗?我怎样才能达到
蟒蛇2
在里面
蟒蛇3
?我已经试着把全球和本地的字典传给
执行程序
中的函数
蟒蛇3
但到目前为止还没什么效果。
---编辑---
在阅读了Martijns的答案之后,我进一步分析了这一点
蟒蛇3
. 在下面的示例中,我给出了
locals()
措辞
d
到
执行程序
但是
d['b']
打印其他东西而不仅仅是打印
乙
.
from sys import version
print(version)
def execute(a, st):
b = 42
d = locals()
exec("b = {}\nprint('b:', b)".format(st), globals(), d)
print(b) # This prints 42
print(d['b']) # This prints 1000000.0
print(id(d) == id(locals())) # This prints True
a = 1.
execute(a, "1.E6*a")
3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]
b: 1000000.0
42
1000000.0
True
的ID比较
D
和
本地人()
显示它们是同一对象。但在这种情况下
乙
应该和
D′b′
. 我的例子有什么问题?