python-15-变量作用域

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
    

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

  2. nonlocal 关键字:用于在嵌套函数中修改外部函数的变量

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

    def outer_function():
        x = 10
    
        def inner_function():
            nonlocal x
            x += 5
            print(x)
    
        inner_function()  # 输出: 15
        print(x)  # 输出: 15
    
    outer_function()
    

四.总结

这里有一个隐藏概念 变量的作用域是在定义是确定,还是在运行时确定?大家理解下这一概念应该能更好的理解这一概念!

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SEEONTIME

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值