如何在函数中创建或使用全局变量?
如何在其他函数中使用一个函数中定义的全局变量?
未能在适当的地方使用全局关键字通常会导致UnboundLocalError。在第一次使用后重新分配局部变量时,UnboundLocalError中解释了这方面的精确规则。一般来说,当寻求解释时,请将其他问题作为该问题的副本,当某人只需要知道全局关键字时,请关闭该问题。
如何在函数中创建或使用全局变量?
如何在其他函数中使用一个函数中定义的全局变量?
未能在适当的地方使用全局关键字通常会导致UnboundLocalError。在第一次使用后重新分配局部变量时,UnboundLocalError中解释了这方面的精确规则。一般来说,当寻求解释时,请将其他问题作为该问题的副本,当某人只需要知道全局关键字时,请关闭该问题。
当前回答
您需要在每个要使用的函数中引用全局变量。
如下:
var = "test"
def printGlobalText():
global var #wWe are telling to explicitly use the global version
var = "global from printGlobalText fun."
print "var from printGlobalText: " + var
def printLocalText():
#We are NOT telling to explicitly use the global version, so we are creating a local variable
var = "local version from printLocalText fun"
print "var from printLocalText: " + var
printGlobalText()
printLocalText()
"""
Output Result:
var from printGlobalText: global from printGlobalText fun.
var from printLocalText: local version from printLocalText
[Finished in 0.1s]
"""
其他回答
您可能需要探索名称空间的概念。在Python中,模块是全局数据的自然位置:
每个模块都有自己的专用符号表,该表被模块中定义的所有函数用作全局符号表。因此,模块的作者可以在模块中使用全局变量,而不用担心与用户的全局变量发生意外冲突。另一方面,如果你知道你在做什么,你可以用与引用它的函数相同的符号modname.itemname来触摸模块的全局变量。
这里描述了模块中全局变量的具体用法-如何在模块之间共享全局变量?,为完整起见,内容如下:
在单个程序中跨模块共享信息的规范方法是创建一个特殊的配置模块(通常称为config或cfg)。只需在应用程序的所有模块中导入配置模块;然后,模块变为可用的全局名称。因为每个模块只有一个实例,所以对模块对象所做的任何更改都会在任何地方反映出来。例如:
文件:config.py
x=0#“x”配置设置的默认值
文件:mod.py
import config
config.x = 1
文件:main.py
import config
import mod
print config.x
如果我正确理解了您的情况,那么您看到的是Python如何处理本地(函数)和全局(模块)命名空间的结果。
假设你有这样一个模块:
# sample.py
_my_global = 5
def func1():
_my_global = 42
def func2():
print _my_global
func1()
func2()
您可能希望它打印42,但实际上它打印5。如上所述,如果向func1()添加一个“全局”声明,那么func2()将打印42。
def func1():
global _my_global
_my_global = 42
这里发生的情况是,Python假设在函数中的任何地方,任何分配给的名称都是该函数的本地名称,除非另有明确说明。如果它只是从一个名称中读取,并且该名称在本地不存在,那么它将尝试在任何包含范围(例如模块的全局范围)中查找该名称。
因此,当将42指定给名称_my_global时,Python将创建一个局部变量,该变量将覆盖同名的全局变量。当func1()返回时,该local超出范围并被垃圾收集;同时,func2()只能看到(未修改的)全局名称。请注意,这个命名空间决定发生在编译时,而不是在运行时——如果在赋值之前读取func1()内部的_my_global值,则会得到UnboundLocalError,因为Python已经决定它必须是一个本地变量,但它还没有与之关联的任何值。但通过使用“global”语句,您告诉Python应该在其他地方查找名称,而不是在本地分配。
(我认为,这种行为主要源于对本地名称空间的优化——如果没有这种行为,Python的VM每次在函数内部分配新名称时都需要执行至少三次名称查找(以确保该名称在模块/内置级别上不存在),这将大大降低非常常见的操作速度。)
有两种方法可以将变量声明为全局变量:
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']
您需要在每个要使用的函数中引用全局变量。
如下:
var = "test"
def printGlobalText():
global var #wWe are telling to explicitly use the global version
var = "global from printGlobalText fun."
print "var from printGlobalText: " + var
def printLocalText():
#We are NOT telling to explicitly use the global version, so we are creating a local variable
var = "local version from printLocalText fun"
print "var from printLocalText: " + var
printGlobalText()
printLocalText()
"""
Output Result:
var from printGlobalText: global from printGlobalText fun.
var from printLocalText: local version from printLocalText
[Finished in 0.1s]
"""
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!")