Python全局变量似乎不适用于各个模块 [英] Python global variables don't seem to work across modules

查看:109
本文介绍了Python全局变量似乎不适用于各个模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码



我想在其他模块中使用全局变量,并将其值更改为传播给其他模块。 b
$ b

a.py:

  x =失败
def changeX( ):
global x
x =ok



b.py:

  from a import x,changeX 
changeX()
print x

如果我运行b.py,我希望它打印ok,但它确实打印失败。



问题




  1. 为什么会这样?


(正在运行python-2.7)

c $ c>来自导入x,changeX 等价于:

 导入a 
x = ax
changeX = a.changeX

换句话说,来自imp ort x 不会创建一个 x ,它会间接到 ax ,它会创建一个新的在 b 模块中使用 current x >斧。因此,后来对 ax 的更改不会影响 bx



要使代码按预期工作,只需将 b.py 中的代码更改为 import a

 导入a b $ b a.changeX()
打印ax

您将拥有更少的混乱导入,更易于读取代码(因为它清楚了什么标识符来自哪里,而无需查看导入列表),循环导入的问题更少(因为并不是所有的标识符都是一次需要的),并且像 reload 这样的工具有更好的工作机会。


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:

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

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".

Questions

  1. Why is that?
  2. How can I make it print "ok" instead?

(Running python-2.7)

解决方案

In short: you can't make it print "ok" without modifying the code.

from a import x, changeX is equivalent to:

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

In other words, from a import x doesn't create an x that indirects to a.x, it creates a new global variable x in the b module with the current value of a.x. From that it follows that later changes to a.x do not affect 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.

这篇关于Python全局变量似乎不适用于各个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆