全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-19 6 分钟 ✍️ juanwangdev

Python变量作用域

变量作用域决定变量的可见范围,Python 采用 LEGB 规则查找变量。

局部变量

函数内定义的变量

Python
def my_function():
    local_var = 10  # 局部变量
    print(local_var)

my_function()  # 10

# print(local_var)  # NameError:外部无法访问

局部变量生命周期

Python
def counter():
    count = 0  # 每次调用重新创建
    count += 1
    return count

print(counter())  # 1
print(counter())  # 1(每次都是新变量)

全局变量

函数外定义的变量

Python
global_var = 100  # 全局变量

def my_function():
    print(global_var)  # 可以访问

my_function()  # 100
print(global_var)  # 100

函数内修改全局变量

Python
global_var = 100

def modify():
    global_var = 200  # 创建同名局部变量,而非修改全局
    print(global_var)  # 200

modify()
print(global_var)  # 100(全局未变)

global 关键字

正确修改全局变量

Python
count = 0

def increment():
    global count  # 声明使用全局变量
    count += 1

increment()
print(count)  # 1

increment()
print(count)  # 2

多个全局变量

Python
x = 10
y = 20

def modify_globals():
    global x, y
    x = 100
    y = 200

modify_globals()
print(x, y)  # 100 200

LEGB 查找规则

查找顺序

Python
L (Local)     → 局部作用域(函数内)
E (Enclosing) → 嵌套作用域(外层函数)
G (Global)    → 全局作用域(模块级别)
B (Built-in)  → 内置作用域(Python 内置函数)

示例演示

Python
x = "global"

def outer():
    x = "enclosing"

    def inner():
        x = "local"
        print(x)  # local(优先局部)

    inner()
    print(x)  # enclosing

outer()
print(x)  # global

# 内置作用域示例
print(len)  # <built-in function len>

去掉各层变量观察查找

Python
x = "global"

def outer():
    x = "enclosing"

    def inner():
        # 无局部 x
        print(x)  # enclosing(查找外层)

    inner()

outer()
Python
# 只有全局
x = "global"

def outer():
    def inner():
        print(x)  # global

    inner()

outer()

nonlocal 关键字

修改嵌套作用域变量

Python
def outer():
    count = 0

    def inner():
        nonlocal count  # 声明使用外层变量
        count += 1
        return count

    return inner

counter = outer()
print(counter())  # 1
print(counter())  # 2

global vs nonlocal

Python
x = "global"

def outer():
    x = "enclosing"

    def inner():
        global x     # 指向全局 x
        x = "modified global"

    inner()
    print(x)  # enclosing(外层未变)

outer()
print(x)  # modified global

作用域最佳实践

避免滥用全局变量

Python
# 不推荐
total = 0
def add(n):
    global total
    total += n

# 推荐:使用参数和返回值
def add(total, n):
    return total + n

函数参数优先

text
# 推荐
def calculate(base, factor):
    return base * factor

result = calculate(10, 2)

要点总结

  1. 局部变量仅函数内可见,函数结束即销毁
  2. 全局变量模块级别可见,函数内可读取
  3. global 关键字声明修改全局变量
  4. nonlocal 关键字声明修改嵌套作用域变量
  5. LEGB 规则:局部 → 嵌套 → 全局 → 内置

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python函数定义与调用
下一篇 → Python可变参数
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库