[英]what makes two python files import a same config file and can influence each other?
maybe this tiltle cannot explain my questions, here has an example. 也许这个小提琴无法解释我的问题,这里有一个例子。
There are three python files, demo.py
、 fun.py
、 config.py
. 一共有三个python文件,
demo.py
, fun.py
, config.py
。
in the config.py
file: 在
config.py
文件中:
from easydict import EasyDict as edict
__C = edict()
cfg = __C
__C.TRAIN = edict()
__C.TRAIN.LEARNING_RATE = 0.001
in the fun.py
: 在
fun.py
:
from config import cfg
def function():
print(cfg.TRAIN.LEARNING_RATE)
cfg.TRAIN.LEARNING_RATE = 1
pass
in the demo.py
: 在
demo.py
:
from config import cfg
from fun import function
cfg.TRAIN.LEARNING_RATE = 0.1
function()
print(cfg.TRAIN.LEARNING_RATE)
run the demo.py
,results in : 运行
demo.py
,结果是:
0.1
1
I am curious about why fun.py
can change the values in the demo.py
although they import a same config file. 我很好奇,为什么
fun.py
可以更改值demo.py
虽然它们导入相同的配置文件。
Well, you answered your own question: they import the same config file. 好吧,您回答了自己的问题:它们导入相同的配置文件。
Keep in mind you're not changing a value in demo.py
or fun.py
. 请记住,您没有更改
demo.py
或fun.py
的值。 Instead, when you do cfg.TRAIN.LEARNING_RATE = 0.1
you're changing the variable in memory cfg
, which is tied to config.py
. 相反,当您执行
cfg.TRAIN.LEARNING_RATE = 0.1
您正在更改内存cfg
的变量,该变量绑定到config.py
。
Since both demo.py
and fun.py
import the same config.py
, the interpreter loads the whole thing into memory once and gives those other two files access to the cfg
variable stored in memory. 由于
demo.py
和fun.py
导入相同的config.py
,因此解释器将整个事件一次加载到内存中,并赋予其他两个文件访问存储在内存中的cfg
变量的权限。 In other words, they're both manipulating the same variable, which they accessed independently. 换句话说,他们都在操纵同一个变量,它们是独立访问的。
(The reason the program never outputs 0.001
is that, while cfg.TRAIN.LEARNING_RATE
is initialized to that value as soon as you load config.py
into memory for the first time, you never actually print it before reassigning it to 0.1
.) (程序从不输出
0.001
的原因是,当cfg.TRAIN.LEARNING_RATE
将config.py
加载到内存时cfg.TRAIN.LEARNING_RATE
被初始化为该值,而在将其重新分配为0.1
之前,您从未真正打印过它。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.