正在设置Python全局变量问题

正在设置Python全局变量问题,python,Python,函数执行完毕后,全局变量不会“保存”。您可以运行下面的代码并查看调试输出 主文件: from GlobalTest import * def init(): #call that function, should set Mode2D to True set2DMode(True) #define it as a global global Mode2D #see what the value is set to now, which is no

函数执行完毕后,全局变量不会“保存”。您可以运行下面的代码并查看调试输出

主文件:

from GlobalTest import *

def init():

    #call that function, should set Mode2D to True
    set2DMode(True)

    #define it as a global
    global Mode2D

    #see what the value is set to now, which is not what I set it to for an unknown reason
    print("Mode:",Mode2D)

init()
全球测试:

Mode2D = False

def set2DMode(mode):
    #define it as global so it uses the one above
    global Mode2D

    #set the GLOBAL variable to the argument
    Mode2D = mode

    #output of what it thinks it is, which is as expected
    print("local var mode =",mode)
    print("Mode2D =", Mode2D)
我的期望:
本地var模式=真
Mode2D=True
模式:真

我得到的结果:
本地var模式=真
Mode2D=True

Mode:False

甚至:您已经破坏了名称空间
set2DMode
仍在查看
GlobalTest.Mode2D
,但您的函数正在打印
Main.Mode2D
。不要破坏名称空间。