全局
一句话解释
全局 refers 到 变量 定义 at 模块 level, and 全局 keyword lets 函数 修改 它们.
用大白话说
全局变量是 定义 at 模块 level (之外任何函数 or 类). 它是 可见贯穿模块. 内部函数, 你能 读取全局变量, 但到 修改它们你 需要 global keyword.
Without 全局, assigning to a variable name inside a function creates a new local variable, even if a global with the same name exists. The 全局 keyword tells Python to use the module-level variable instead.
Overusing global variables is generally discouraged because it makes code harder to test and debug. Prefer passing values as function parameters and returning results. Use 全局 sparingly, mainly for module-level configuration.
示例
counter = 0 # global variable
def increment():
global counter # declare we want to modify the global
counter += 1
def read_counter():
return counter # reading globals doesn't need "global"
increment()
increment()
print(read_counter()) # 2全局 变量 是 模块-level. Use 全局 keyword 内部 函数 到 修改 它们.
常见混淆
容易混淆的对象: nonlocal
关键区别: 全局 修改 模块-level 变量. nonlocal 修改 变量 in enclosing 函数 (for nested 函数/闭包). Use 全局 for 模块 作用域; nonlocal for enclosing 函数 作用域.
相关术语
相关资源
相关课程
- 函数
全局 keyword.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。