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