标题说出我所知道的一切
def fun():
global v
v = 1
exec("global " + "k")
exec("k" + " = 1")
fun()
print(v)
# prints 1
print(k)
# NameError: name 'k' is not defined
我希望算法为v和k都打印1,但出现错误。
答案 0 :(得分:0)
只需将globals()
添加到exec
函数调用中即可:
def fun():
global v
v = 1
exec("k" + " = 1", globals())
fun()
print(v)
# prints 1
print(k)
# prints 1
答案 1 :(得分:0)
如果您需要使用exec,则可以像这样分配k的值
def fun():
exec("globals()['k'] = " + "1")
fun()
print(k) # output is 1