python-15变量作用域
一.说明
什么是作用域?作用域是指变量在代码中可被访问的范围,这个概念在编程中实在太平常了!理解作用域这一概念在解决命名冲突及调试非常重要!
二.作用域解析顺序(LEGB规则)
Python按照以下顺序解析变量的作用域,称为LEGB规则:
- Local: 当前函数内部的变量;
- Enclosing: 外部函数的局部变量(如果有嵌套函数);
- Global: 当前模块中的全局变量;
- Built-in: 内置的变量和函数;
x = "global"
def outer_function():
x = "enclosing"
def inner_function():
x = "local"
print(x) # 输出: local
inner_function()
print(x) # 输出: enclosing
outer_function()
print(x) # 输出: global
#################
x = 0
def increment():
print(x)
def demo():
x = 100
increment()
demo() #输出: 0
###################
x = 0
def demo():
x = 100
def increment():
nonlocal x
print(x)
increment()
demo() #输出: 100
#################
x = 0
def demo():
x = 100
def increment():
global x
print(x)
increment()
demo() #输出: 0
三.global和
nonlocal
-
global
关键字:用于在函数内部修改全局变量我们先来看卡在python中不使用**
global
** 关键字x = 0 def increment(): x += 1 print(x) #报错:local variable 'x' referenced before assignment increment() print(x) ############ x = 0 def increment(): x = 1 print(x) #输出:1 increment() print(x) #输出:0
我们再看看使用**
global
** 关键字x = 0 def increment(): global x x += 1 increment() print(x) # 输出: 1
这个概念理解了吧!很简单。。
-
nonlocal
关键字:用于在嵌套函数中修改外部函数的变量这个概念也简单,看下面例子
def outer_function(): x = 10 def inner_function(): nonlocal x x += 5 print(x) inner_function() # 输出: 15 print(x) # 输出: 15 outer_function()
四.总结
这里有一个隐藏概念 变量的作用域是在定义是确定,还是在运行时确定?大家理解下这一概念应该能更好的理解这一概念!
创作整理不易,请大家多多关注 多多点赞,有写的不对的地方欢迎大家补充,我来整理,再次感谢!