python nonlocal/global ---内部作用域中改变外部变量

nonlocal,作用:使外层函数中的变量能被内层函数中被查找到,使用,或更改。
global,作用:在外层函数中使用和改变全局变量

原因:在python中,局部作用域里面的代码可以读取外部作用域(包括全局作用域)的变量,但是规定一般情况不能更改外部作用域的变量的值。一旦更改,会报错。为改变这种状态,引入关键字:nonlocal。
例如:
1.用全局变量,在内层函数中修改值,不使用nonlocal

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
x=2                 #全局变量
def func_outer():   #外层函数                   
    print (x)       #只调用全局变量,不改变其值
    def func_inner():   #内层函数     
        x=x+1           #改变全局变量,不使用nonlocal    
        print(x)
    func_inner()
func_outer()
#结果:报错:x---局部变量没有被定义就使用

2.内层函数使用、改变外层函数变量,不使用nonlocal

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def func_outer():                 #外层函数 
    x=2                      #建立一个变量       
    print (x)
    def func_inner():        #内层函数
        x=x+1               #改变外层函数变量
        print(x)
    func_inner()
func_outer()
#结果:局部变量没有被定义就使用

在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在)
(导致“UnboundLocalError: local variable ‘foobar’ referenced before assignment”)

3.外层函数改变全局变量,不使用:global

x=0
def func_outer():
    x+=1
    print("change x ",x)
func_outer()
#结果:UnboundLocalError: local variable 'x' referenced before assignment

4.使用,改变外部变量,使用nonlocal

def func_outer():
    x=2                                              #外层函数
    def func_inner():
        nonlocal x                               #使用nonlocal 使用外层函数的变量
        x=x+1
        print(x)
    func_inner()
    print("change x ",x)
func_outer()
#结果:
3
change x  3

5.使用,改变全局变量,使用golobal


x=0
def func_outer():                                                #外层函数
    global x
    x+=1
    def func_inner():
        #nonlocal x                               #使用nonlocal 使用外层函数的变量
        #x=x+1
        print(x)
    func_inner()
    print("change x ",x)
func_outer()
#结果:
1
change x  1

5.在外部函数和内部函数同时改变全局变量

x=0
def func_outer():                                                #外层函数
    global x
    x+=1
    def func_inner(x):
        #nonlocal x                  #使用nonlocal会报错
        x=x+1
        print('内层函数',x)
    func_inner(x)
    print("外层函数",x)
func_outer()
print('全局变量',x)
#结果:
内层函数 2
外层函数 1
全局变量 1
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值