为什么我不能在另一个函数中在exec中声明一个函数?我真的不知道为什么会发生这种事,有没有办法让这件事成功。我发现了这个:Invoking problem with function defined in exec(),但这不是我想要的,在我的例子中,我不希望执行代码是任意的。
def test():
exec("""
def this():
print('this')
def main():
this()
main()
""")
test()返回:
Traceback (most recent call last):
File "/t.py", line 12, in <module>
test()
File "/t.py", line 2, in test
exec("""
File "<string>", line 8, in <module>
File "<string>", line 6, in main
NameError: name 'this' is not defined当我在函数之外执行执行时,它工作得很好,为什么?:
exec("""
def this():
print('this')
def main():
this()
main()
""")发布于 2022-03-21 15:42:12
这是我努力让它发挥作用的方法
从错误中,我猜您可以在全局环境中使用exec()创建对象,但不能在函数中使用exec()将对象添加到全局环境中。因此,系统将其视为本地exec()变量,但未能读取该变量。
因此,我试图添加一个全球宣言,它起了作用:
def test():
exec("""
global this
def this():
print('this')
def main():
this()
main()
""")
test()结果:
this但是,它可能会覆盖其他全局变量,因为我现在可以在this()之外调用test()。
>>> this()
thishttps://stackoverflow.com/questions/71560113
复制相似问题