跳到主要内容

Python globals()

globals() 方法返回一个字典,其中包含当前程序的所有全局变量和符号。

示例

print(globals())

输出

{'In': ['', 'globals()'],
'Out': {},
'_': '',
'__': '',
'___': '',
'__builtin__': <module 'builtins' (内置)>,
'__builtins__': <module 'builtins' (内置)>,
'__name__': '__main__',
'_dh': ['/home/repl'],
'_i': '',
'_i1': 'globals()',
'_ih': ['', 'globals()'],
'_ii': '',
'_iii': '',
'_oh': {},
'_sh': <module 'IPython.core.shadowns' from '/usr/local/lib/python3.5/dist-packages/IPython/core/shadowns.py'>,
'exit': <IPython.core.autocall.ExitAutocall at 0x7fbc60ca6c50>,
'get_ipython': <bound method InteractiveShell.get_ipython of <IPython.core.interactiveshell.InteractiveShell object at 0x7fbc6478ee48>>,
'quit': <IPython.core.autocall.ExitAutocall at 0x7fbc60ca6c50>}

globals() 语法

globals() 方法的语法是:

globals()

globals() 参数

globals() 方法不接受任何参数。

globals() 返回值

globals() 方法返回当前全局符号表的字典。

示例:Python globals()

age = 23

globals()['age'] = 25
print('年龄是:', age)

输出

年龄是: 25

Python 编译器维护着一个符号表,其中包含有关正在编写的程序的必要信息。在 Python 中有两种类型的符号表 - 局部全局

全局符号表存储与程序的全局范围(整个程序内)相关的所有信息。我们可以使用 globals() 方法访问这个符号表。

通常,Python 程序员使用 globals() 方法来修改代码中的任何全局变量。

在这个示例中,我们使用 globals() 方法和字典键 ['age'] 将年龄变量改为 25

推荐阅读: