我试图创建一个给定值的类,然后根据给定的索引执行字符串列表中的字符串,以更改全局变量。但我不明白为什么执行的字符串不能更改var1和var0的值。
global var0, var1
class Change:
def __init__(self, executed):
self.executed = executed
def changeGlobals(self):
global var0, var1
exec(self.executed)
var0 = 0
var1 = 1
executed = 'var0 = var0+1; var1 = var1+1;'
var = Change(executed)
var.changeGlobals()
# is supposed to print 'var0 is 1, var1 is 2'
print('var0 is '+str( var0 )+', var1 is '+str( var1 ))
# actually prints 'var0 is 0, var1 is 1'
您不是在changeGlobals((方法中更改变量的值,而是像这样更改:
global var0, var1
class Change:
def __init__(self, executed):
self.executed = executed
def changeGlobals(self):
global var0, var1
var0 += 1
var1 += 1
exec(self.executed)
另一种方法是将executed = 'var0 = var0+1; var1 = var1+1;'
更改为executed = 'global var0, var1; var0 = var0+1; var1 = var1+1;'
,实际发现传递给exec的字符串中的全局定义工作于