Python中的dir()和locals()之间有什么区别吗?

gri*_*yvp 8 python

根据Python文档,两者dir()(没有args)并locals()评估调用的变量列表local scope.第一个返回名称列表,第二个返回名称 - 值对的字典.这是唯一的区别吗?这总是有效吗?

assert dir() == sorted( locals().keys() )
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 6

dir()不带参数调用时的输出几乎相同locals(),但dir()返回字符串列表并locals()返回字典,您可以更新该字典以添加新变量.

dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.


locals(...)
    locals() -> dictionary

    Update and return a dictionary containing the current scope's local variables.
Run Code Online (Sandbox Code Playgroud)

类型:

>>> type(locals())
<type 'dict'>
>>> type(dir())
<type 'list'>
Run Code Online (Sandbox Code Playgroud)

使用locals()以下方法更新或添加新变量

In [2]: locals()['a']=2

In [3]: a
Out[3]: 2
Run Code Online (Sandbox Code Playgroud)

dir()然而,使用这不起作用:

In [7]: dir()[-2]
Out[7]: 'a'

In [8]: dir()[-2]=10

In [9]: dir()[-2]
Out[9]: 'a'

In [10]: a
Out[10]: 2
Run Code Online (Sandbox Code Playgroud)

  • 由于Python优化了对函数中局部变量的访问,因此通常不可能使用`locals()`字典来更改局部变量,这就是文档警告它的原因. (3认同)