![](/img/trans.png)
[英]Can I create a data file in Python and import it to other python files
[英]what makes two python files import a same config file and can influence each other?
也許這個小提琴無法解釋我的問題,這里有一個例子。
一共有三個python文件, demo.py
, fun.py
, config.py
。
在config.py
文件中:
from easydict import EasyDict as edict
__C = edict()
cfg = __C
__C.TRAIN = edict()
__C.TRAIN.LEARNING_RATE = 0.001
在fun.py
:
from config import cfg
def function():
print(cfg.TRAIN.LEARNING_RATE)
cfg.TRAIN.LEARNING_RATE = 1
pass
在demo.py
:
from config import cfg
from fun import function
cfg.TRAIN.LEARNING_RATE = 0.1
function()
print(cfg.TRAIN.LEARNING_RATE)
運行demo.py
,結果是:
0.1
1
我很好奇,為什么fun.py
可以更改值demo.py
雖然它們導入相同的配置文件。
好吧,您回答了自己的問題:它們導入相同的配置文件。
請記住,您沒有更改demo.py
或fun.py
的值。 相反,當您執行cfg.TRAIN.LEARNING_RATE = 0.1
您正在更改內存cfg
的變量,該變量綁定到config.py
。
由於demo.py
和fun.py
導入相同的config.py
,因此解釋器將整個事件一次加載到內存中,並賦予其他兩個文件訪問存儲在內存中的cfg
變量的權限。 換句話說,他們都在操縱同一個變量,它們是獨立訪問的。
(程序從不輸出0.001
的原因是,當cfg.TRAIN.LEARNING_RATE
將config.py
加載到內存時cfg.TRAIN.LEARNING_RATE
被初始化為該值,而在將其重新分配為0.1
之前,您從未真正打印過它。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.