nonlocal和global的区别

本文深入探讨了Python中不同作用域的变量修改规则,包括全局变量、局部变量及嵌套函数中变量的修改,并展示了如何使用global和nonlocal关键字来改变变量的作用域。
x = 0
def outer():
    x = 1
    def inner():
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

结果是:

inner: 2
outer: 1
global: 0
global

适用于函数内部修改全局变量的值

x = 0
def outer():
    x = 1
    def inner():
        global x
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

结果是:

inner: 2
outer: 1
global: 2
nonlocal

适用于嵌套函数中内部函数修改外部变量的值

x = 0
def outer():
    x = 1
    def inner():
        nonlocal x
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

结果是:

inner: 2
outer: 2
global: 0

如果没有使用以上关键字,对全局变量或者外部变量进行修改,python会默认将全局变量隐藏起来

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值