Python globals()

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

示例

print(globals())

输出

{'In': ['', 'globals()'],
 'Out': {},
 '_': '',
 '__': '',
 '___': '',
 '__builtin__': <module 'builtins' (built-in)>,
 '__builtins__': <module 'builtins' (built-in)>,
 '__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('The age is:', age)

输出

The age is: 25

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

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

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

在本例中,我们使用 globals() 方法和字典键 ['age']age 变量更改为 25


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战