2016-07-28 125 views
0

我有一個主文件和數百個導入到主文件中的子文件。另外,我在main.py文件中定義了全局字典。在多個python文件中使用全局變量

# ../myproject/main.py 
import sub1.py 
import sub2.py 

global dict_test={} 

dict_test["fruit"]="apple" 

我怎樣才能在我的sub1.py,sub2.py文件中使用這個dict_test字典?

+0

爲什麼不把字典放在一個模塊(比如''globalvars.py'')中,並直接從它導入? – NuclearPeon

+0

我不想添加任何其他模塊,是否有任何解決方法使用sub1.py中的dict_test? –

+0

@gokulchand是的,主要你可以從一個子模塊中調用一個函數作爲參數。在這個函數中,你可以訪問這個'全局'字典。 – mhoff

回答

0

你不能直接這樣做,因爲它會導致一個循環輸入,其中main導入sub1sub1main導入字典。

前進的方向是通過引入包含共享資源的第三個模塊來打破依賴關係。

`constanst.py` 
============== 
dict_test = {} 
dict_test["fruit"] = "apple" 

main.py 
======= 
from constants import dict_test 

sub1.py 
======= 
from constants import dict_test