小编svl*_*yso的帖子

python 3中exec函数的奇怪行为

为什么这段代码不起作用?

class wrapper(dict):
    pass

script = """
def foo():
    print(10)

foo()
"""
exec(script, wrapper())
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到了这条消息:

File "test.py", line 29, in <module>
exec(script, wrapper())
 File "<string>", line 5, in <module>
 File "<string>", line 3, in foo
KeyError: 'print'
Run Code Online (Sandbox Code Playgroud)

如果我将最后一行更改为

exec(script, {})
Run Code Online (Sandbox Code Playgroud)

然后一切正常。

我不明白,为什么完全透明的字典继承会改变脚本行为?

python

6
推荐指数
1
解决办法
115
查看次数

标签 统计

python ×1