0
点赞
收藏
分享

微信扫一扫

python-15一篇文章帮你理解python变量作用域

python-15变量作用域

一.说明

什么是作用域?作用域是指变量在代码中可被访问的范围,这个概念在编程中实在太多了!理解作用域这一概念在解决命名冲突及调试非常重要!

二.作用域解析顺序(LEGB规则)

Python按照以下顺序解析变量的作用域,称为LEGB规则:

  1. Local: 当前函数内部的变量;
  2. Enclosing: 外部函数的局部变量(如果有嵌套函数);
  3. Global: 当前模块中的全局变量;
  4. 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

三.globalnonlocal

  1. 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

这个概念理解了吧!很简单。。

  1. nonlocal这个概念也简单,看下面例子

def outer_function():
    x = 10

    def inner_function():
        nonlocal x
        x += 5
        print(x)

    inner_function()  # 输出: 15
    print(x)  # 输出: 15

outer_function()

四.总结

通过以上例子和**global** 、nonlocal

创作整理不易,请大家多多关注 多多点赞,有写的不对的地方欢迎大家补充,我来整理,再次感谢!

举报

相关推荐

0 条评论