简体   繁体   English

导入了Python模块; 为什么重新分配其中的成员也会影响其他地方的进口?

[英]Imported a Python module; why does a reassigning a member in it also affect an import elsewhere?

I am seeing Python behavior that I don't understand. 我看到了我不理解的Python行为。 Consider this layout: 考虑这个布局:

project
|   main.py
|   test1.py
|   test2.py
|   config.py

main.py: main.py:

import config as conf
import test1
import test2

print(conf.test_var)
test1.test1()
print(conf.test_var)
test2.test2()

test1.py: test1.py:

import config as conf

def test1():
    conf.test_var = 'test1'

test2.py: test2.py:

import config as conf

def test2():
    print(conf.test_var)

config.py: config.py:

test_var = 'initial_value'

so, python main.py produce: 所以, python main.py产生:

initial_value
test1
test1

I am confused by the last line. 我对最后一行感到困惑。 I thought that it would print initial_value again because I'm importing config.py in test2.py again, and I thought that changes that I've made in the previous step would be overwritten. 我认为它会再次打印initial_value ,因为我再次在test2.py导入config.py ,我认为我在上一步中所做的更改将被覆盖。 Am I misunderstanding something? 我误会了什么吗?

Python caches imported modules. Python缓存导入的模块。 The second import call doesn't reload the file. 第二个import调用不会重新加载该文件。

test2.py test2.py

import config as conf

def test2():
    print(id(conf.test_var))
    print(conf.test_var)

test1.py test1.py

import config as conf

def test1():
    conf.test_var = 'test1'
    print(id(conf.test_var))

Change code like this. 改变这样的代码。

And run main.py 并运行main.py

initial_value
140007892404912
test1
140007892404912
test1

So, you can see that in both cases you are changing value of the same variable. 因此,您可以看到,在这两种情况下,您都在更改同一变量的值。 See these id 's are same. 看到这些id是一样的。

You edited the test_var in test1.py and then just printed it again using test2.py . 您编辑的test_vartest1.py ,然后就再次打印它使用test2.py Importing again does not change the fact than you assigned new value to the variable - it does not "reset" the value to the first one. 再次导入并不会改变事实,而不是为变量赋予新值 - 它不会将值“重置”到第一个值。

You changed the value of test_var when you ran test1 , and so it was already changed when you ran test2 . 运行test1时更改了test_var的值,因此在运行test2时它已经更改。

That variable will not reset for every file in which you import it. 该变量不会为您导入它的每个文件重置。 It will be one value for everything. 这将是一切的价值。

no, you're changing with test1() in the config.py a constant value. 不,您在config.py中使用test1()更改为常量值。 This won't be resetted. 这不会被重置。 Since you print it in test2() , the modified value gets printed again. 由于您在test2()打印它,因此再次打印修改后的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM