在 Python[如无说明特指 Python3]中, 有将近 70 个内置函数[1],他们不需要用户定义或者声明引入,即可直接使用。在最近的项目中使用到了 globals()和 locals()两个函数,说一下自己的理解。

首先 globals 的作用是负责管理全局变量,其官方说明文档中写到:

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

globals()方法返回的是一个包含当前全局变量的 dict,所以一切用于操作 dict 的方法都可以用于操作 globals()的返回值,比如当我们需要修改全局变量的时候就可以使用globals().update(),同时,globals()是可写的,也就是说,可以修改该字典中的键值,可新增和删除键值对。

相对的,locals()的作用是负责管理局部变量,其官方说明文档中写到:

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary.

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()类似,locals()返回的是局部变量的 dict,同样可以使用管理 dict 的方式管理局部变量,但是官方文档里多了一句说明,locals()是不可修改 dict 中已存在的键值的,也不能 pop 移除键值对,但是可以新增键值对。

总结:

  1. globals()和 locals(),它们提供了基于 dict 的访问局部和全局变量的方式。

  2. globals()和 locals()可以提供一个动态创建变量的机制,比如动态生成变量名的字符串,然后利用 globals()和 locals()返回的 dict 创建键值对,对应的字符串就是 key,然后赋值对应的值就可以了。例如,globals()[self_defined_str] = ‘new value’

  3. globals()是可写的,即,可修改该 dict 中的键值,可新增和删除键值对。而 locals()是不可修改 dict 中已存在的键值的,也不能 pop 移除键值对,但是可以新增键值对。

Reference:

  1. https://docs.python.org/3/library/functions.html