如何在函数中创建或使用全局变量?
如何在其他函数中使用一个函数中定义的全局变量?
未能在适当的地方使用全局关键字通常会导致UnboundLocalError。在第一次使用后重新分配局部变量时,UnboundLocalError中解释了这方面的精确规则。一般来说,当寻求解释时,请将其他问题作为该问题的副本,当某人只需要知道全局关键字时,请关闭该问题。
如何在函数中创建或使用全局变量?
如何在其他函数中使用一个函数中定义的全局变量?
未能在适当的地方使用全局关键字通常会导致UnboundLocalError。在第一次使用后重新分配局部变量时,UnboundLocalError中解释了这方面的精确规则。一般来说,当寻求解释时,请将其他问题作为该问题的副本,当某人只需要知道全局关键字时,请关闭该问题。
当前回答
实际上,您并没有将全局变量存储在本地变量中,只是创建了对原始全局引用引用的同一对象的本地引用。请记住,Python中的几乎所有内容都是引用对象的名称,在通常的操作中不会复制任何内容。
如果您不必显式指定标识符何时引用预定义的全局变量,那么您可能必须显式指定何时标识符是新的局部变量(例如,使用JavaScript中的“var”命令)。由于在任何严肃和非平凡的系统中,局部变量比全局变量更常见,因此Python的系统在大多数情况下更有意义。
你可能有一种语言试图猜测,如果存在的话使用一个全局变量,如果不存在的话创建一个局部变量。然而,这很容易出错。例如,导入另一个模块可能会无意中引入一个同名的全局变量,从而改变程序的行为。
其他回答
尽管这已经得到了回答,但我还是再次给出了解决方案,因为我更喜欢单线这是如果您希望在函数中创建全局变量
def someFunc():
x=20
globals()['y']=50
someFunc() # invoking function so that variable Y is created globally
print(y) # output 50
print(x) #NameError: name 'x' is not defined as x was defined locally within function
对于并行执行,如果您不了解正在发生的情况,全局变量可能会导致意外的结果。下面是在多处理中使用全局变量的示例。我们可以清楚地看到,每个过程都使用自己的变量副本:
import multiprocessing
import os
import random
import sys
import time
def worker(new_value):
old_value = get_value()
set_value(random.randint(1, 99))
print('pid=[{pid}] '
'old_value=[{old_value:2}] '
'new_value=[{new_value:2}] '
'get_value=[{get_value:2}]'.format(
pid=str(os.getpid()),
old_value=old_value,
new_value=new_value,
get_value=get_value()))
def get_value():
global global_variable
return global_variable
def set_value(new_value):
global global_variable
global_variable = new_value
global_variable = -1
print('before set_value(), get_value() = [%s]' % get_value())
set_value(new_value=-2)
print('after set_value(), get_value() = [%s]' % get_value())
processPool = multiprocessing.Pool(processes=5)
processPool.map(func=worker, iterable=range(15))
输出:
before set_value(), get_value() = [-1]
after set_value(), get_value() = [-2]
pid=[53970] old_value=[-2] new_value=[ 0] get_value=[23]
pid=[53971] old_value=[-2] new_value=[ 1] get_value=[42]
pid=[53970] old_value=[23] new_value=[ 4] get_value=[50]
pid=[53970] old_value=[50] new_value=[ 6] get_value=[14]
pid=[53971] old_value=[42] new_value=[ 5] get_value=[31]
pid=[53972] old_value=[-2] new_value=[ 2] get_value=[44]
pid=[53973] old_value=[-2] new_value=[ 3] get_value=[94]
pid=[53970] old_value=[14] new_value=[ 7] get_value=[21]
pid=[53971] old_value=[31] new_value=[ 8] get_value=[34]
pid=[53972] old_value=[44] new_value=[ 9] get_value=[59]
pid=[53973] old_value=[94] new_value=[10] get_value=[87]
pid=[53970] old_value=[21] new_value=[11] get_value=[21]
pid=[53971] old_value=[34] new_value=[12] get_value=[82]
pid=[53972] old_value=[59] new_value=[13] get_value=[ 4]
pid=[53973] old_value=[87] new_value=[14] get_value=[70]
试试看:
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
实际上,您并没有将全局变量存储在本地变量中,只是创建了对原始全局引用引用的同一对象的本地引用。请记住,Python中的几乎所有内容都是引用对象的名称,在通常的操作中不会复制任何内容。
如果您不必显式指定标识符何时引用预定义的全局变量,那么您可能必须显式指定何时标识符是新的局部变量(例如,使用JavaScript中的“var”命令)。由于在任何严肃和非平凡的系统中,局部变量比全局变量更常见,因此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']