You can use a global variable in other functions by declaring it as global
in each function that assigns to it:
(您可以通过声明为使用其他功能的全局变量global
指派每个功能吧:)
globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global
keyword.
(我想这是因为全局变量是如此危险,Python希望通过显式要求使用global
关键字来确保您真正知道这就是要使用的内容。)
See other answers if you want to share a global variable across modules.
(如果要在模块之间共享全局变量,请参见其他答案。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…