如果使用全局变量的方式可能会被解释为对局部变量的赋值,则需要在函数中使用全局关键字。如果没有全局关键字,您将创建一个局部变量,它隐藏函数范围中的全局变量。
以下是几个例子:global_var = 1
def example1():
# global keyword is not needed, local_var will be set to 1.
local_var = global_var
def example2():
# global keyword is needed, if you want to set global_var,
# otherwise you will create a local variable.
global_var = 2
def example3():
# Without using the global keyword, this is an error.
# It's an attempt to reference a local variable that has not been declared.
global_var += 1