Python global scope troubles

独自空忆成欢 提交于 2019-12-11 11:43:04

问题


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

回答1:


There are several important things to note here.

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.

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.

This means that after the first line of main.py:

from File2 import *

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.

After the second line:

updateX()

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

The third line:

print x

prints __main__'s x, which is still 5.



来源:https://stackoverflow.com/questions/23942626/python-global-scope-troubles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!