我已阅读无法通过 exec() 语句更改函数中的全局变量?,但这不是我的情况。
当我运行时test(),它会引发异常UnboundLocalError: local variable 'var' referenced before assignment,看起来好像exec('global var', globals())不起作用。
var = 1
def test():
exec('global var', globals()) # The effect it achieves is different from `global var`, why?
var += 1
test()
print(var)
但是,如果我将功能更改为以下内容,它会起作用:
def test():
exec('global var', globals())
exec('var += 1', globals())
不知道为什么,谁能解释一下?