Python-keyword-global & nonlocal

本文详细解析了Python中global及nonlocal关键字的使用方法。通过具体示例对比了使用与不使用global关键字时,对全局变量操作的影响;并介绍了如何在嵌套函数中正确使用nonlocal来修改外部函数的变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. global  #消除python对global variable的屏蔽(shadowing)作用

1.1 如果只是 Access 变量,不必加global

1.2如果在 函数中需要修改global变量,则需加global

>>> t = 5

>>> hex(id(t))

'0x64320250'

>>> def withoutGlobal():

        t = 10

        print("without global id of t is:",hex(id(t)))

>>> withoutGlobal()

without global id of t is: 0x643202f0

>>> def withGlobal():

        global t

        t = 10

        print("with global id of t is:",hex(id(t)))

>>> hex(id(t))

'0x64320250'

>>> withGlobal()

with global id of t is: 0x643202f0

>>> # after call withGlobal()

>>> hex(id(t))

'0x643202f0'

>>> t

10



2.nonlocal 用在内部函数中

2.1 错误例子

>>> def fun1():

               x = 5 #相当于fun2()的全局变量

                         def fun2():

                          x *= x

               return fun2()

>>> fun1()

UnboundLocalError: local variable 'x' referenced before assignment

2.2 正确例子

>>> def fun1():

                 x = 5

                def fun2():

                          nonlocal x

                          x *= x

                         return x

                  return fun2()

>>> fun1()

25



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值