以下代码在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")
Python2
张照片:
2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
('b:', 1000000.0)
1000000.0
Python3
张照片:
3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]
b: 1000000.0
42
为什么Python2
会将execute
函数中的变量b
绑定到exec
函数字符串中的值,而Python3
不会这样做?我怎样才能达到Python3
分之Python2
的行为呢?我已经try 过将全局和局部的字典传递到Python3
中的exec
函数,但到目前为止没有任何效果.
--- EDIT ---
在阅读了Martijns的答案后,我用Python3
进一步分析了这个问题.在下面的例子中,我给locals()
的词义是d
到exec
,但是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
对d
和locals()
的ID进行比较表明,它们是同一个对象.但在这些条件下,b
应该与d['b']
相同.我的例子有什么不对?