以下代码给出了不同的输出Python2
and in 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")
Python2
prints:
2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
('b:', 1000000.0)
1000000.0
Python3
prints:
3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]
b: 1000000.0
42
为什么Python2
绑定变量b
在 - 的里面execute
函数的字符串中的值exec
函数,同时Python3
不这样做吗?我怎样才能实现以下行为Python2
in Python3
?我已经尝试将全局变量和本地变量的字典传递给exec
函数于Python3
,但到目前为止没有任何效果。
- - 编辑 - -
阅读 Martijns 的回答后,我进一步分析了这一点Python3
。在下面的例子中我给出locals()
字典作为d
to exec
, but d['b']
打印除打印以外的其他内容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
and locals()
表明它们是同一个对象。但在这些条件下b
应该是一样的d['b']
。我的例子有什么问题吗?