为什么函数没有在exec下的另一个函数中定义?

2024-03-28 14:50:20 发布

您现在位置:Python中文网/ 问答频道 /正文

test_str = '''
def test():
    print("test")

def hello():
    print("hello")
    test()

hello()
'''
def main():
    exec(test_str, globals(), locals())

main()

输出:

hello
name 'test' is not defined

但是如果我把locals()改成globals(),一切都好!为什么?你知道吗


Tags: nametesthelloismaindefnotexec