如何在函数中创建或使用全局变量?
如何在其他函数中使用一个函数中定义的全局变量?
未能在适当的地方使用全局关键字通常会导致UnboundLocalError。在第一次使用后重新分配局部变量时,UnboundLocalError中解释了这方面的精确规则。一般来说,当寻求解释时,请将其他问题作为该问题的副本,当某人只需要知道全局关键字时,请关闭该问题。
如何在函数中创建或使用全局变量?
如何在其他函数中使用一个函数中定义的全局变量?
未能在适当的地方使用全局关键字通常会导致UnboundLocalError。在第一次使用后重新分配局部变量时,UnboundLocalError中解释了这方面的精确规则。一般来说,当寻求解释时,请将其他问题作为该问题的副本,当某人只需要知道全局关键字时,请关闭该问题。
当前回答
写入全局数组的显式元素显然不需要全局声明,尽管“批发”写入它确实有这样的要求:
import numpy as np
hostValue = 3.14159
hostArray = np.array([2., 3.])
hostMatrix = np.array([[1.0, 0.0],[ 0.0, 1.0]])
def func1():
global hostValue # mandatory, else local.
hostValue = 2.0
def func2():
global hostValue # mandatory, else UnboundLocalError.
hostValue += 1.0
def func3():
global hostArray # mandatory, else local.
hostArray = np.array([14., 15.])
def func4(): # no need for globals
hostArray[0] = 123.4
def func5(): # no need for globals
hostArray[1] += 1.0
def func6(): # no need for globals
hostMatrix[1][1] = 12.
def func7(): # no need for globals
hostMatrix[0][0] += 0.33
func1()
print "After func1(), hostValue = ", hostValue
func2()
print "After func2(), hostValue = ", hostValue
func3()
print "After func3(), hostArray = ", hostArray
func4()
print "After func4(), hostArray = ", hostArray
func5()
print "After func5(), hostArray = ", hostArray
func6()
print "After func6(), hostMatrix = \n", hostMatrix
func7()
print "After func7(), hostMatrix = \n", hostMatrix
其他回答
如果您有一个同名的局部变量,您可能需要使用globals()函数。
globals()['your_global_var'] = 42
如果要在函数中引用全局变量,可以使用global关键字声明哪些变量是全局变量。您不必在所有情况下都使用它(正如这里有人错误地宣称的那样)-如果表达式中引用的名称无法在定义该函数的函数的局部作用域中找到,则会在全局变量中查找该名称。
但是,如果您分配给函数中未声明为全局的新变量,则它将隐式声明为局部变量,并且它可能会覆盖同名的任何现有全局变量。
此外,全局变量是有用的,与一些OOP狂热者的说法相反——特别是对于较小的脚本,OOP是过度的。
Initialized = 0 #Here This Initialized is global variable
def Initialize():
print("Initialized!")
Initialized = 1 #This is local variable and assigning 1 to local variable
while Initialized == 0:
这里我们比较全局变量Initialized为0,因此当循环条件为true时
Initialize()
函数将被调用。循环将是无限的
#if we do Initialized=1 then loop will terminate
else:
print("Lets do something else now!")
有两种方法可以将变量声明为全局变量:
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']
对于并行执行,如果您不了解正在发生的情况,全局变量可能会导致意外的结果。下面是在多处理中使用全局变量的示例。我们可以清楚地看到,每个过程都使用自己的变量副本:
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]