以下代码给出了 inPython2
和 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
印刷:
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
的变量绑定到函数字符串中的值,而没有这样做?我怎样才能实现in的行为?我已经尝试将字典传递给全局变量和局部变量以在其中起作用,但到目前为止没有任何效果。b
execute
exec
Python3
Python2
Python3
exec
Python3
- - 编辑 - -
在阅读了 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
和的 id 比较locals()
表明它们是同一个对象。但在这些条件下b
应该是一样的d['b']
。我的例子有什么问题?