我知道使用全局变量有时是最方便的事情,尤其是在使用类使最简单的事情变得如此困难的情况下(例如,multiprocessing)。我在声明全局变量时遇到了同样的问题,并通过一些实验解决了这个问题。
g_c 没有被您的类中的run 函数更改的原因是对g_c 中的全局名称的引用不是在函数中精确建立的。 Python 处理全局声明的方式实际上是相当棘手的。命令global g_c有两个作用:
将键 "g_c" 输入到内置函数 globals() 可访问的字典中的前提条件。但是,在为其分配值之前,该键不会出现在字典中。
(可能)改变 Python 在当前方法中查找变量 g_c 的方式。
对(2)的全面理解特别复杂。首先,它只是潜在地改变,因为如果在方法中没有对名称 g_c 赋值,那么 Python 默认会在 globals() 中搜索它。这实际上是一件相当普遍的事情,就像在代码开头一直导入的方法模块中引用的情况一样。
但是,如果在方法中任何地方出现赋值命令,Python 默认会在局部变量中查找名称g_c。即使在实际赋值之前发生引用也是如此,这将导致经典错误:
UnboundLocalError: local variable 'g_c' referenced before assignment
现在,如果声明 global g_c 出现在方法中任何地方,即使在任何引用或赋值之后,Python 也会默认在全局变量中查找名称 g_c。但是,如果您觉得是实验性的并将声明放在引用之后,您将收到警告:
SyntaxWarning: name 'g_c' is used prior to global declaration
如果你仔细想想,Python 中全局声明的工作方式显然与 Python 的正常工作方式相一致。只是当您真正希望全局变量起作用时,规范变得烦人。
这里是总结了我刚才所说的代码(还有一些观察):
g_c = 0
print ("Initial value of g_c: " + str(g_c))
print("Variable defined outside of method automatically global? "
+ str("g_c" in globals()))
class TestClass():
def direct_print(self):
print("Directly printing g_c without declaration or modification: "
+ str(g_c))
#Without any local reference to the name
#Python defaults to search for the variable in globals()
#This of course happens for all the module names you import
def mod_without_dec(self):
g_c = 1
#A local assignment without declaring reference to global variable
#makes Python default to access local name
print ("After mod_without_dec, local g_c=" + str(g_c))
print ("After mod_without_dec, global g_c=" + str(globals()["g_c"]))
def mod_with_late_dec(self):
g_c = 2
#Even with a late declaration, the global variable is accessed
#However, a syntax warning will be issued
global g_c
print ("After mod_with_late_dec, local g_c=" + str(g_c))
print ("After mod_with_late_dec, global g_c=" + str(globals()["g_c"]))
def mod_without_dec_error(self):
try:
print("This is g_c" + str(g_c))
except:
print("Error occured while accessing g_c")
#If you try to access g_c without declaring it global
#but within the method you also alter it at some point
#then Python will not search for the name in globals()
#!!!!!Even if the assignment command occurs later!!!!!
g_c = 3
def sound_practice(self):
global g_c
#With correct declaration within the method
#The local name g_c becomes an alias for globals()["g_c"]
g_c = 4
print("In sound_practice, the name g_c points to: " + str(g_c))
t = TestClass()
t.direct_print()
t.mod_without_dec()
t.mod_with_late_dec()
t.mod_without_dec_error()
t.sound_practice()