变量作用域 #

作用域决定了变量的可见范围。

一、局部作用域 #

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

my_function()
# print(local_var)  # NameError: 局部变量不能在外部访问

二、全局作用域 #

python
global_var = 100  # 全局变量

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

my_function()
print(global_var)  # 100

三、global关键字 #

python
counter = 0

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

increment()
print(counter)  # 1

# 不使用global会创建局部变量
def wrong_increment():
    counter = 100  # 局部变量
    counter += 1

四、nonlocal关键字 #

python
def outer():
    count = 0
    
    def inner():
        nonlocal count  # 引用外层函数的变量
        count += 1
    
    inner()
    print(count)  # 1

outer()

五、LEGB规则 #

Python查找变量的顺序(从内到外):

  1. Local - 局部作用域
  2. Enclosing - 嵌套作用域
  3. Global - 全局作用域
  4. Built-in - 内置作用域
python
x = "global"

def outer():
    x = "enclosing"
    
    def inner():
        x = "local"
        print(x)  # local
    
    inner()
    print(x)  # enclosing

outer()
print(x)  # global

六、内置作用域 #

python
# 内置函数在任何地方都可以访问
print(len([1, 2, 3]))  # 3

# 可以覆盖内置函数(不推荐)
def len(x):
    return 0

print(len([1, 2, 3]))  # 0

七、闭包 #

python
def make_counter():
    count = 0
    
    def counter():
        nonlocal count
        count += 1
        return count
    
    return counter

counter = make_counter()
print(counter())  # 1
print(counter())  # 2
print(counter())  # 3

八、总结 #

关键字 用途
global 声明使用全局变量
nonlocal 声明使用外层函数变量

LEGB查找顺序: Local → Enclosing → Global → Built-in

最后更新:2026-03-16