11

代码

我想在其他模块中使用全局变量,并将其值的更改“传播”到其他模块。

一个.py:

x="fail"
def changeX():
    global x
    x="ok"

b.py:

from a import x, changeX
changeX()
print x

如果我运行 b.py,我希望它打印“ok”,但它确实打印“fail”。

问题

  1. 这是为什么?
  2. 我怎样才能让它打印“ok”呢?

(运行 python-2.7)

4

3 回答 3

15

简而言之:你不能在不修改代码的情况下让它打印“ok”。

from a import x, changeX相当于:

import a
x = a.x
changeX = a.changeX

换句话说,from a import x它不会创建一个x间接指向 的,而是在模块中a.x创建一个新的全局变量,其当前值为。由此可见,后来的变化不影响。xba.xa.xb.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.

于 2012-11-15T17:59:02.427 回答
3

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.

于 2013-07-23T17:26:30.037 回答
2

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]
于 2012-11-15T18:17:23.253 回答