我看到了我不理解的Python行为.考虑这个布局:
project
| main.py
| test1.py
| test2.py
| config.py
Run Code Online (Sandbox Code Playgroud)
main.py:
import config as conf
import test1
import test2
print(conf.test_var)
test1.test1()
print(conf.test_var)
test2.test2()
Run Code Online (Sandbox Code Playgroud)
test1.py:
import config as conf
def test1():
conf.test_var = 'test1'
Run Code Online (Sandbox Code Playgroud)
test2.py:
import config as conf
def test2():
print(conf.test_var)
Run Code Online (Sandbox Code Playgroud)
config.py:
test_var = 'initial_value'
Run Code Online (Sandbox Code Playgroud)
所以,python main.py生产:
initial_value
test1
test1
Run Code Online (Sandbox Code Playgroud)
我对最后一行感到困惑.我认为,这将打印initial_value,因为我再次导入config.py在test2.py再次,我认为,我在上一步中所做的更改将被覆盖.我误会了什么吗?
test2.py
import config as conf
def test2():
print(id(conf.test_var))
print(conf.test_var)
Run Code Online (Sandbox Code Playgroud)
test1.py
import config as conf
def test1():
conf.test_var = 'test1'
print(id(conf.test_var))
Run Code Online (Sandbox Code Playgroud)
改变这样的代码.
并运行 main.py
initial_value
140007892404912
test1
140007892404912
test1
Run Code Online (Sandbox Code Playgroud)
因此,您可以看到,在这两种情况下,您都在更改同一变量的值.看到这些id是一样的.