无法访问更新的全局变量的值
假设我有两个 Python 文件:
abc.py:
from .config import *
update_a()
print_a() # prints 5
print(a) # prints 2 rather than 5 even after calling update_a() and using global in update_a()
config.py:
a = 2
def update_a():
global a
a = 5
def print_a():
global a
print(a) # prints 5
config.py从 访问时,全局变量 in似乎没有更新的值abc.py。
回答
当您执行 import say 时from .config import *,该变量a将作为本地范围导入。任何修改,a将在范围内发生在abc.pyNOT中config.py而调用update_a()和print_a()被修改的变量a内config.py