为什么python字符串不能从类内部更改全局变量?

时间:2020-10-12 15:21:55

标签: python class global

我试图制作一个被赋予值的类,然后根据给定的索引在字符串列表中执行一个字符串,以更改全局变量。但是我无法弄清楚为什么执行的字符串不能更改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'

1 个答案:

答案 0 :(得分:0)

您不是在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的字符串中的全局定义起作用了