编程语言
首页 > 编程语言> > python-如何从locals()分配一个值给具有相同名称的局部变量?

python-如何从locals()分配一个值给具有相同名称的局部变量?

作者:互联网

这有效:

def foo():
    locals().update({'bar': 12})
    print(locals()['bar'])  # 12

这将失败:

def foo():
    locals().update({'bar': 12})
    bar = locals()['bar']  # KeyError: 'bar'
    print(bar)

解决方法:

https://docs.python.org/3/library/functions.html#locals

Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

编辑:但是如上所述,bar = 12当然有效:

>>> def foo():
...     bar = 12
...     bar_ = locals()["bar"]
...     print(bar_)
...     
... 
>>> foo()
12

标签:local-variables,python
来源: https://codeday.me/bug/20191025/1926792.html