我是這個網站的新手,我可以在以下方面提供一些幫助嗎?
我有一個main.py包含字典的程式loaddict。
我在主程式之外有一個模塊,其中包含多個函式,所有這些函式都需要loaddict主程式中的字典。
有沒有辦法loaddict從這個模塊中的多個函式訪問字典而不設定loaddict為所有函式的引數?
以下代碼不起作用,因為即使使用關鍵字,剩余的函式仍然無法訪問loaddict該函式。dgmglobal
## 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
uj5u.com熱心網友回復:
你的錯誤
在我看來,你的錯誤只是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 parametr 'loaddict' has been removed...
'''
def dgm(other_parameters):
# no global keyword inside the function
print(loaddict['key1'])
''' The function modify loaddict value and call a function from main.py
'''
def function1(some_parameters):
# the following instruction is able to modify the value of '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的是在對key1function1()loaddict
有用的鏈接是Python Module Variables。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/530846.html
標籤:Python变量模块
