当我在python shell中执行以下代码时,
def foo():
bar = 0
vars()['bar'] = 1
print('within function: ' + str(bar))
foo()
baz = 0
vars()['baz'] = 1
print('inline: ' + str(baz))
我明白了
within function: 0
inline: 1
为什么通过vars()
设置变量似乎是内联的,但是从函数内部调用时却行不通?