Skip to content

作用域

一句话解释

作用域 是 区域 的 code 哪里 变量 name 是 可见 and accessible.

用大白话说

Scope determines where a variable name can be accessed. Python has four scope levels, remembered by the LEGB rule:

  1. Local — variables defined inside a function. Only visible within that function.
  2. Enclosing — variables in the outer function, visible to nested functions (closures).
  3. Global — variables defined at module level. Visible throughout the module.
  4. Built-in — Python's built-in names like len, print, int. Always available.

Use 全局 to modify a global variable from inside a function, and nonlocal to modify an enclosing variable. Without these, assigning inside a function creates a new local variable instead.

示例

python
x = 10  # global

def outer():
    y = 20  # enclosing

    def inner():
        z = 30  # local
        print(x, y, z)  # can see all three

    inner()

outer()

# global keyword
counter = 0
def increment():
    global counter
    counter += 1

作用域 follows LEGB: 局部, Enclosing, 全局, 构建-in. Use 全局/nonlocal 到 修改 外部 变量.

常见混淆

  • 容易混淆的对象: 命名空间

    关键区别: 作用域 是 区域 哪里 names 是 可见. 命名空间 是 实际 映射 从 names 到 对象. 作用域 是 关于 visibility; 命名空间 是 关于 storage mechanism.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表