12.python-使用非当前作用域变量的方法

本文探讨了Python中全局变量及非本地局部变量的使用方法,包括如何在函数内部正确修改全局变量,以及如何声明非本地变量进行修改或引用。

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

# 全局变量(global variable)& 非本地局部变量(nonlocal variable)
# 关键字global&nonlocal
# ===================================================


gcount = 0


def global_test():
    try:
        gcount += 1
        print(gcount)
    except Exception as e:
        print(str(Exception))  # <class 'Exception'>
        print(str(e))  # local variable 'gcount' referenced before assignment


print('Do not declare the global variable before changing it:')
global_test()


# 运行异常:
# UnboundLocalError: local variable 'gcount' referenced before assignment

# ===================================================
# 在函数内部 修改 全局变量之前,必须先再次声明全局变量,正确打开方式如下

def global_test_1():
    global gcount
    gcount += 1
    print(gcount)


print('Declare the global variable before changing it:')
global_test_1()  # 1


# ===================================================
# 若不修改全局变量,可不在局部声明全局变量

def global_test_2():
    print(gcount)


print('Needn\'t declare the global variable before referencing it:')
global_test_2()  # 1


# ===================================================
# 局部变量的用法


def outer():
    count = 0

    def inner():
        def inner_in():
            nonlocal count  # 修改非当前作用域且非全局变量,必须声明,若只是引用,不必声明
            count += 1
            return count

        return inner_in()

    return inner


inner_func = outer()
print(inner_func())  # 1
print(inner_func())  # 2
print(inner_func())  # 3

inner_func_1 = outer()
print(inner_func_1())  # 1
print(inner_func_1())  # 2
print(inner_func_1())  # 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值