Python 本地更新不起作用 [英] Python Locals update not working

查看:62
本文介绍了Python 本地更新不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

def foo():共同 = {'abc':'xyz'}打印(当地人())当地人().更新(普通)打印(当地人(),ABC)富()

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

如果我在函数外运行它,它就可以工作

common = {'abc' : 'xyz'}打印(当地人())当地人().更新(普通)打印(当地人(),ABC)

解决方案

根据 本地人文档:

<块引用>

注意本词典内容不可修改;更改可能不会影响解释器使用的局部变量和自由变量的值.

所以它不起作用,因为它不打算工作.但是现在要回答您的问题,它在全局范围内有效,因为可以修改 globals全局文档 没有说明不应修改此 [...]".

而且,很明显,当您处于全局范围内时, global 是 locals:

<预><代码>>>>globals() 是 locals()真的

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

Why below is not working inside function but working outside?

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

foo()

Error : NameError: global name 'abc' is not defined

If i run it outside function, it works

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

解决方案

According to the 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.

So it's not working because it's not intended to work. But to answer your question now, it works in the global scope because modifying the globals is possible, the globals documentation don't have the note telling "this [...] should not be modified".

And, obviously, when you're in the global scope, global is locals:

>>> globals() is locals()
True

So you're modifying globals, which is permitted.

这篇关于Python 本地更新不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆