如何在函数中创建或使用全局变量?

如何在其他函数中使用一个函数中定义的全局变量?


未能在适当的地方使用全局关键字通常会导致UnboundLocalError。在第一次使用后重新分配局部变量时,UnboundLocalError中解释了这方面的精确规则。一般来说,当寻求解释时,请将其他问题作为该问题的副本,当某人只需要知道全局关键字时,请关闭该问题。


当前回答

试试看:

def x1():
    global x
    x += 1
    print('x1: ', x)

def x2():
    global x
    x = x+1
    print('x2: ', x)

x = 5
print('x:  ', x)
x1()
x2()

# Output:
# x:   5
# x1:  6
# x2:  7

其他回答

您可以在其他函数中使用全局变量,方法是在为其赋值的每个函数中将其声明为全局变量:

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

由于不清楚globvar=1是创建本地变量还是更改全局变量,Python默认创建本地变量,并使用全局关键字显式选择其他行为。

如果要在模块间共享全局变量,请参阅其他答案。

类似此代码:

myVar = 12

def myFunc():
  myVar += 12

Key:

如果在字符串外部声明变量,它将变为全局变量。

如果在字符串中声明变量,它将变为本地变量。

如果要在字符串中声明全局变量,请在要声明的变量之前使用关键字global:

myVar = 124
def myFunc():
  global myVar2
  myVar2 = 100
myFunc()
print(myVar2)

然后文档中有100个。

除了已经存在的答案之外,为了使这一问题更加令人困惑:

在Python中,仅在函数内部引用的变量是隐式全局。如果在任何地方为变量分配了新值在函数体中,假设它是局部的。如果变量如果在函数中分配了一个新值,则变量为隐式本地,您需要将其显式声明为“全局”。虽然一开始有点令人惊讶,但片刻的思考解释了这一方面,要求全局分配变量提供了防止意外的副作用。另一方面,如果全球对于所有全局引用都是必需的时间您必须将对内置函数或导入模块的组件。这种混乱会破坏全球宣言对识别副作用。

来源:Python中局部和全局变量的规则是什么?。

有两种方法可以将变量声明为全局变量:

1.在函数内部分配变量并使用全局线

def declare_a_global_variable():
    global global_variable_1
    global_variable_1 = 1

# Note to use the function to global variables
declare_a_global_variable() 

2.分配变量外部函数:

global_variable_2 = 2

现在我们可以在其他函数中使用这些声明的全局变量:

def declare_a_global_variable():
    global global_variable_1
    global_variable_1 = 1

# Note to use the function to global variables
declare_a_global_variable() 
global_variable_2 = 2

def print_variables():
    print(global_variable_1)
    print(global_variable_2)
print_variables() # prints 1 & 2

注1:

如果要更改另一个函数(如update_variables())中的全局变量,则应在分配变量之前在该函数中使用全局行:

global_variable_1 = 1
global_variable_2 = 2

def update_variables():
    global global_variable_1
    global_variable_1 = 11
    global_variable_2 = 12 # will update just locally for this function

update_variables()
print(global_variable_1) # prints 11
print(global_variable_2) # prints 2

注2:

在函数内部不使用全局行时,列表和字典变量的注释1有一个例外:

# declaring some global variables
variable = 'peter'
list_variable_1 = ['a','b']
list_variable_2 = ['c','d']

def update_global_variables():
    """without using global line"""
    variable = 'PETER' # won't update in global scope
    list_variable_1 = ['A','B'] # won't update in global scope
    list_variable_2[0] = 'C' # updated in global scope surprisingly this way
    list_variable_2[1] = 'D' # updated in global scope surprisingly this way

update_global_variables()

print('variable is: %s'%variable) # prints peter
print('list_variable_1 is: %s'%list_variable_1) # prints ['a', 'b']
print('list_variable_2 is: %s'%list_variable_2) # prints ['C', 'D']

我补充了这一点,因为我在其他任何答案中都没有看到它,它可能对正在与类似问题作斗争的人有用。globals()函数返回一个可变的全局符号字典,您可以在其中“神奇地”使数据可用于代码的其余部分。例如:

from pickle import load
def loaditem(name):
    with open(r"C:\pickle\file\location"+"\{}.dat".format(name), "rb") as openfile:
        globals()[name] = load(openfile)
    return True

and

from pickle import dump
def dumpfile(name):
    with open(name+".dat", "wb") as outfile:
        dump(globals()[name], outfile)
    return True

将只允许您将变量转储/加载到全局命名空间中。超级方便,没有麻烦,没有麻烦。很确定它只是Python 3。