我有这个:
>>> d = {}
>>> d["hi"] = 12345
>>> d1 = {}
>>> d1["hiiii"] = 1234590
我知道为什么会出现下面的错误。这是因为 exec 找不到变量 hi 和 hiiii。
>>> exec "print hi, hiiii"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'hi' is not defined
>>> exec "print hiiii"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'hiiii' is not defined
现在它可以工作了,因为 exec 能够在字典 d 和 d1 中找到 hi 和 hiiii 变量
>>> exec "print hi, hiiii" in d , d1
12345 1234590
到目前为止一切顺利。
问题:
现在,当我打印 d 时,我看到它已被修改并打印了很多键、值对..为什么? 但是在打印 d1 时我没有看到很多键、值对,为什么会这样?
最佳答案
这在 the docs 中有解释。 :
As a side effect, an implementation may insert additional keys into the dictionaries given besides those corresponding to variable names set by the executed code. For example, the current implementation may add a reference to the dictionary of the built-in module
__builtin__
under the key__builtins__
(!).
关于python - 需要澄清 python 中 exec 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18730518/