简体   繁体   English

Python全局变量似乎不适用于模块

[英]Python global variables don't seem to work across modules

Code

I'd like to use a global variable in other modules with having changes to its value "propagated" to the other modules. 我想在其他模块中使用全局变量,并将其值的变化“传播”到其他模块。

a.py: a.py:

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

b.py: b.py:

from a import x, changeX
changeX()
print x

If I run b.py, I'd want it to print "ok", but it really prints "fail". 如果我运行b.py,我希望它打印“ok”,但它确实打印“失败”。

Questions 问题

  1. Why is that? 这是为什么?
  2. How can I make it print "ok" instead? 如何让它打印“确定”呢?

(Running python-2.7) (运行python-2.7)

In short: you can't make it print "ok" without modifying the code. 简而言之:如果不修改代码,就无法打印“ok”。

from a import x, changeX is equivalent to: from a import x, changeX相当于:

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

In other words, from a import x doesn't create an x that indirects to ax , it creates a new global variable x in the b module with the current value of ax . 换句话说, from a import x不创建一个间接到axx ,它在b模块中创建一个新的全局变量x ,其当前值为ax From that it follows that later changes to ax do not affect bx . 由此可见,后来对ax更改不会影响bx

To make your code work as intended, simply change the code in b.py to import a : 要使代码按预期工作,只需更改b.py的代码即可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. 您将获得更少杂乱的导入,更容易阅读代码(因为很清楚标识符来自哪里而不查看导入列表),循环导入的问题较少(因为不是一次都需要所有标识符),并且更有可能像reload工作的工具。

Also you can use mutable container, for example list: 您也可以使用可变容器,例如list:

a.py a.py

x = ['fail']

def changeX():
    x[0] = 'ok'

b.py b.py

from a import changeX, x

changeX()
print x[0]

You can also add another import statement after changeX . 您还可以在changeX之后添加另一个import语句。 This would turn the code from b.py into 这会将代码从b.py转换为

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. 这说明通过调用changeX ,只更改了模块a x Importing it again, binds the updated value again to the identifier x . 再次导入它,将更新后的值再次绑定到标识符x

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

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