代码
我想在其他模块中使用全局变量,并将其值的更改“传播”到其他模块。
一个.py:
x="fail"
def changeX():
global x
x="ok"
b.py:
from a import x, changeX
changeX()
print x
如果我运行 b.py,我希望它打印“ok”,但它确实打印“fail”。
问题
- 这是为什么?
- 我怎样才能让它打印“ok”呢?
(运行 python-2.7)
我想在其他模块中使用全局变量,并将其值的更改“传播”到其他模块。
一个.py:
x="fail"
def changeX():
global x
x="ok"
b.py:
from a import x, changeX
changeX()
print x
如果我运行 b.py,我希望它打印“ok”,但它确实打印“fail”。
(运行 python-2.7)
简而言之:你不能在不修改代码的情况下让它打印“ok”。
from a import x, changeX
相当于:
import a
x = a.x
changeX = a.changeX
换句话说,from a import x
它不会创建一个x
间接指向 的,而是在模块中a.x
创建一个新的全局变量,其当前值为。由此可见,后来的变化不影响。x
b
a.x
a.x
b.x
To make your code work as intended, simply change the code in b.py
to import a
:
import a
a.changeX()
print a.x
You will have less cluttered imports, easier to read code (because it's clear what identifier comes from where without looking at the list of imports), less problems with circular imports (because not all identifiers are needed at once), and a better chance for tools like reload
to work.
You can also add another import statement after changeX
. This would turn the code from b.py into
from a import x, changeX
changeX()
from a import x
print x
This illustrates that by calling changeX
, only x
in module a
is changed. Importing it again, binds the updated value again to the identifier x
.
Also you can use mutable container, for example list:
a.py
x = ['fail']
def changeX():
x[0] = 'ok'
b.py
from a import changeX, x
changeX()
print x[0]