导入的变量更新未反映在父模块中

问题描述

我有两个模块,主要模块和更新模块。

在主要方面,我声明了一个引用字典和每个值的列表。在更新中,我更新了年龄,但是我看不到更新再次反映在主模块中。

main module

candidates = {'goutham': {'Age': 30},'teja':{'Age': 27}}

for s in candidates:
    portfolio[s] = [0,0] # some value which i use for other calculations

update module
from main import *

portfolio['goutham'][0] = 32

现在,当我回到主体并打印作品集['goutham']。它仍然显示为[0,0]

解决方法

例如当您运行我添加的{'goutham': [32,0],'teja': [0,0]}时,这应该可以打印run.py

main.py

candidates = {'goutham': {'Age': 30},'teja':{'Age': 27}}
portfolio = {candidate:[0,0] for candidate in candidates.keys()}

update.py

from main import *
portfolio['goutham'][0] = 32

run.py

import update
from main import *
print(portfolio)

作为旁注:现在,模块导入时正在执行的模块中。如果这是您的主要逻辑,请考虑将其放在某个main()函数中,而不要依赖导入时的隐式执行。