【问题标题】:Access variables from main program in python从python中的主程序访问变量
【发布时间】:2023-02-13 16:49:16
【问题描述】:
我是这个网站的新手,我可以在以下方面得到一些帮助吗?
我有一个包含字典loaddict 的main.py 程序。
我在主程序之外有一个模块,其中包含多个函数,所有这些函数都需要主程序中的字典loaddict。
有没有办法从这个模块中的多个函数访问字典loaddict,而无需将loaddict设置为所有函数的参数?
以下代码不起作用,因为即使使用关键字global,剩余的函数仍然无法从函数dgm访问loaddict。
## main program (main.py)
## user inputs data into dictionary: loaddict = {some data}
import BeamDiagram.dgm(loaddict, other parameters)
## module (BeamDiagram.py)
def dgm(loaddict, other parameters):
global loaddict
## some calculations, this part is fine
def function1(some parameters):
## calculations that requires loaddict
def function2(some parameters):
## calculations that requires loaddict
def function3(some parameters):
## calculations that requires loaddict
【问题讨论】:
标签:
python
variables
module
【解决方案1】:
你的错误:脚本中的导入BeamDiagram.py
在我看来你的错误只是import指令,所以在你的代码中只需要一个正确的import:
from main import loaddict
下面我向您展示了我在我的系统中创建的 2 个文件(这两个文件都在同一个文件夹/home/frank/stackoverflow 中)。
主程序
loaddict = {'key1': 'value1'}
''' The function print the value of 'key1'
'''
def print_dict():
print(loaddict['key1'])
在main.py中,我创建了函数print_dict(),它由脚本BeamDiagram.py导入,因为它导入了字典loaddict(BeamDiagram.py的代码见下文)
BeamDiagram.py
'''
Module BeamDiagram.py
'''
from main import loaddict, print_dict
''' In the function the parameter 'loaddict' has been removed...
'''
def dgm(other_parameters):
# no global keyword inside the function
print(loaddict['key1'])
''' function1 modify loaddict value and call a function from main.py
'''
def function1(some_parameters):
# the following instruction is able to modify the value of associated to 'key1'
loaddict['key1'] = 'value2'
print_dict() # print 'value2' on standard output
dgm('other_params')
function1('some_params')
脚本BeamDiagram.py调用函数dgm()和function1(),这意味着:
-
loaddict (dgm()) 的读取权限是可能的
-
loaddict (function1()) 的写权限是可能的
-
key1值的修改在main.py中可见,实际上print_dict1()打印value2,这是key1在function1()做了之后的值写权限到loaddict
有用的链接是Python Module Variables。