Python3中global和nonlocal去区别

变量的作用域如下

  • L (Local) 局部作用域
  • E (Enclosing) 闭包函数外的函数中
  • G (Global) 全局作用域
  • B (Built-in) 内建作用域
x = int(2.9)  # 内建作用域
 
g_count = 0  # 全局作用域
def outer():
    o_count = 1  # 闭包函数外的函数中
    def inner():
        i_count = 2  # 局部作用域

以 L –> E –> G –>B 的规则查找,即:在局部找不到,便会去局部外的局部找(例如闭包),再找不到就会去全局找,再者去内建中找。Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如 if/elif/else/、try/except、for/while等)是不会引入新的作用域的,也就是说这些语句内定义的变量,外部也可以访问,如下代码:

if True:
    msg = '123'
print(msg)  # 123

接着说global和nonlocal

global是直接去全局找变量

nonlocal不断去上一级上变量

# -*-coding:utf8-*-

a = 10


def t():
    a = 100

    def inner1():
        b= 1000

        def inner():
            nonlocal a
            print(a)
        inner()
    inner1()


t()  # 100  首先去inner1里面找有没有a,没有,就去t里面找,找到了,输出结果
# -*-coding:utf8-*-

a = 10


def t():
    a = 100

    def inner1():
        ab= 1000

        def inner():
            global a
            print(a)
        inner()
    inner1()


t()  # 100  直接去找global变量 

参考链接:http://www.runoob.com/python3/python3-function.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值