![](/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.