gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:07 25 4
gpt4 key购买 nike

这个有效:

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

关于python - 如何将 locals() 中的值分配给具有相同名称的局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50155039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com