Python全局范围的麻烦 [英] Python global scope troubles
问题描述
我无法在Python中修改不同文件之间的全局变量.例如:
I'm having trouble modifying global variables between different files in Python. For example:
File1.py:
x = 5
File2.py:
from File1 import *
def updateX():
global x
x += 1
main.py:
from File2 import *
updateX()
print x #prints 5
推荐答案
这里要注意几件重要的事情.
There are several important things to note here.
首先,global
不是全局的.真正的全局事物(如内置函数)存储在__builtin__
模块或Python 3中的builtins
中.global
表示模块级.
First, global
isn't global. The really global things, like built-in functions, are stored in the __builtin__
module, or builtins
in Python 3. global
means module-level.
第二,当您使用import *
时,将获得与import *
所使用的模块中的名称相同的名称的新变量,它们引用相同的对象.这意味着如果您随后在一个模块中重新分配变量,则另一个模块将看不到更改.另一方面,使可变对象可变是两个模块都看到的变化.
Second, when you import *
, you get new variables with the same names as the ones in the module you import *
'd from, referring to the same objects. That means if you then reassign the variable in one module, the other doesn't see the change. On the other hand, mutating a mutable object is a change both modules see.
这意味着在main.py
的第一行之后:
This means that after the first line of main.py
:
from File2 import *
File1
,File2
和__main__
(运行主脚本的模块)都具有引用同一个5
对象的单独的x
变量. File2
和__main__
也具有引用updateX
函数的updateX
变量.
File1
, File2
, and __main__
(the module the main script runs in) all have separate x
variables referring to the same 5
object. File2
and __main__
also have updateX
variables referring to the updateX
function.
第二行之后:
updateX()
仅将File2
的x
变量重新分配给6
. (该函数记录了它的定义位置,因此它更新了File2
的x
而不是__main__
的.)
Only File2
's x
variable is reassigned to 6
. (The function has a record of where it was defined, so it updates File2
's x
instead of __main__
's.)
第三行:
print x
打印__main__
的x
,仍然是5.
这篇关于Python全局范围的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!