为什么这段代码不起作用?
class wrapper(dict):
pass
script = """
def foo():
print(10)
foo()
"""
exec(script, wrapper())
当我跑步时,我收到了这条消息:
File "test.py", line 29, in <module>
exec(script, wrapper())
File "<string>", line 5, in <module>
File "<string>", line 3, in foo
KeyError: 'print'
如果我将最后一行更改为
exec(script, {})
然后一切都好。
我无法理解,为什么完全透明的字典继承会改变脚本行为?