python global和nonlocal_python的global和nonlocal

The global statement can be used to indicate that particular variables live in the global scope and should be rebound there; the nonlocal statement indicates that particular variables live in an enclosing scope and should be rebound there.

还是看python代码来理解吧,这是官方的示例,注释是麦新杰加的:

def scope_test():

def do_local():

spam = "local spam" #do_local()函数本地的变量,谁都不影响

def do_nonlocal():

nonlocal spam

spam = "nonlocal spam" #申明这个spam变量是来自外层namespace

def do_global():

global spam

spam = "global spam" #申明这个spam变量来自全局namespace,注意,这个全局变量在此之前还不存在

spam = "test spam"

do_local()

print("After local assignment:", spam)

do_nonlocal()

print("After nonlocal assignment:", spam)

do_global()

print("After global assignment:", spam)

scope_test()

print("In global scope:", spam)

这段代码运行的结果如下:

After local assignment: test spam

After nonlocal assignment: nonlocal spam

After global assignment: nonlocal spam # 代码执行到这里,实际上是申明了一个全局变量并给它赋值。

In global scope: global spam

这样,我们就理解了python的global和nonlocal申明的含义。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值