Python 本地更新不起作用

标签 python python-2.7 python-3.x

这个问题在这里已经有了答案:





Why is it bad idea to modify locals in python?

(5 个回答)


5年前关闭。




为什么下面不是在函数内部工作而是在外部工作?

def foo():
    common = {'abc' : 'xyz'}
    print(locals())
    locals().update(common)
    print(locals(),abc)

foo()

错误:NameError:未定义全局名称“abc”

如果我在函数外运行它,它会起作用
common = {'abc' : 'xyz'}
print(locals())
locals().update(common)
print(locals(),abc)

最佳答案

根据locals documentation :

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.



所以它不起作用,因为它不打算工作。但是现在要回答您的问题,它在全局范围内有效,因为修改了 globals是可能的,globals documentation没有说明“这 [...] 不应该被修改”。

而且,显然,当您处于全局范围内时, global 是 locals:
>>> globals() is locals()
True

所以你正在修改全局变量,这是允许的。

关于Python 本地更新不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600997/

相关文章:

python - 将 PDF 的 CreationTime 转换为 Python 中的可读格式

python - 使用表单发布请求,然后能够保存它在单独请求中返回的数据

python - 无法理解一些 python 元组语法

python-3.x - 对 numpy 的同情导致 AttributeError : 'Symbol' object has no attribute 'cos'

unit-testing - Python 3 urlopen 上下文管理器模拟

django - 如何在Elasticsearch中同时搜索单数和复数形式的单词?

Python浅拷贝和深拷贝中使用append方法

python - 数组上的广播掩码操作

python - 查找另一个列表中每个子列表的超集索引

python - 有没有更好的(即更 Pythonic 的)方法来处理打包/解包函数参数?