6人参与 • 2025-06-11 • Python
变量作用域指的是变量在程序中可以被访问的范围。就像生活中:
python有四种作用域,按照从内向外的顺序:
作用域类型 | 描述 | 查找顺序 | 生命周期 |
---|---|---|---|
局部(local) | 函数内部定义的变量 | 1 | 函数执行期间 |
闭包(enclosing) | 嵌套函数中 外部函数的变量 | 2 | 只要内部函数存在 |
全局(global) | 模块级别定义的变量 | 3 | 模块加载期间 |
内置(built-in) | python内置的变量和函数 | 4 | python解释器运行期间 |
当访问一个变量时,python按以下顺序查找: [局部作用域] → [闭包作用域] → [全局作用域] → [内置作用域] ↑ ↑ ↑ ↑ 函数内部 嵌套函数的外部函数 模块级别 python内置
def my_function(): x = 10 # 局部变量 print(x) my_function() # 输出: 10 print(x) # 报错: nameerror,x在函数外部不可见
出现在嵌套函数中:
def outer(): y = 20 # 闭包作用域变量 def inner(): print(y) # 可以访问外部函数的变量 inner() outer() # 输出: 20 print(y) # 报错: nameerror,y在outer外部不可见
z = 30 # 全局变量 def func(): print(z) # 可以访问全局变量 func() # 输出: 30 print(z) # 输出: 30
print(len("hello")) # len是内置函数 # 当我们使用len()时,python最后会在内置作用域中找到它
x = "global" # 全局变量 def test(): x = "local" # 局部变量,遮蔽了全局x print(x) # 输出: local test() print(x) # 输出: global
当需要在 函数内部 修改 全局变量 时:
count = 0 def increment(): global count # 声明使用全局变量 count += 1 increment() print(count) # 输出: 1
在 嵌套函数 中修改 外部函数 的变量:
def outer(): num = 10 def inner(): nonlocal num # 声明使用闭包作用域变量 num = 20 inner() print(num) # 输出: 20 outer()
x = 5 def func(): print(x) # 报错: unboundlocalerror x = 10 # 这会使x成为局部变量,遮蔽全局x # 解决方案: 使用global声明 def fixed_func(): global x print(x) # 输出: 5 x = 10
funcs = [] for i in range(3): def func(): return i funcs.append(func) print([f() for f in funcs]) # 输出: [2, 2, 2] 不是预期的[0,1,2] # 解决方案1: 使用默认参数 funcs = [] for i in range(3): def func(i=i): # 创建闭包 return i funcs.append(func) # 解决方案2: 使用lambda funcs = [lambda i=i: i for i in range(3)]
python使用legb规则来查找变量:
l: local - 当前函数内部 e: enclosing - 嵌套函数的 外层函数 g: global - 模块级别 b: built-in - python内置
def outer(): y = "enclosing" def inner(): z = "local" print(z) # 1. local中找到 print(y) # 2. enclosing中找到 print(x) # 3. global中找到 print(len) # 4. built-in中找到 inner() x = "global" outer()
# config.py debug = false timeout = 30 # app.py import config def connect(): if config.debug: print(f"连接超时设置为: {config.timeout}") # 连接逻辑...
def counter(): count = 0 def increment(): nonlocal count count += 1 return count return increment c = counter() print(c(), c(), c()) # 输出: 1 2 3
理解python变量作用域的关键点:
通过合理利用作用域规则,你可以写出更清晰、更模块化的python代码!
以上就是一文全面详解python变量作用域的详细内容,更多关于python变量作用域的资料请关注代码网其它相关文章!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论