Python 函数作用域

本文详细解析了Python中变量的作用域规则,包括函数内外变量的访问与修改限制,并介绍了global和nonlocal关键字的使用方法。

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

外部不能访问函数内部变量

>>> def fun1():
    x = 1

>>> print(x)

#结果
Traceback (most recent call last):
    File "<pyshell#6>", line 1, in <module>
        print(x)
NameError: name 'x' is not defined

函数内部能够访问函数外部变量:

>>> x = 123
>>> def fun2():
            print(x)
#结果:
>>> fun2()  #调用函数
123 

函数里面不能修改函数外部变量:

>>> x = 123
>>> def  fun3():
        x = x + 1
        print(x)
#结果
Traceback (most recent call last):
    File "<pyshell#19>", line 1, in <module>
        fun3()
    File "<pyshell#17>", line 2, in fun3
        x = x+1
UnboundLocalError: local variable 'x' referenced before assignment

函数里面和函数外部变量名相同:

>>> x = 123
>>> print(x, id(x))
123 8791238636176
>>> def fun4():
        x = 456
        print(x, id(x))
>>> fun4()
#结果
456 45350000

说明

1.变量是先定义,再使用。

2.如果在最近的作用域里有定义,就会使用最近作用域的变量。

3.如果在函数里面没有定义,它会往它的外层去找。

4.如果外层有定义,就使用.

global(全局变量)

>>> x = 123
>>> def fun1():
    global x
    x+=1
    return x

>>> fun1()
124

nonlocal(上一级函数中的局部变量)

在函数嵌套函数的情况下,同样也有函数作用域的问题,python3中提供了方便,只需要使用nonlocal就可以在里层函数内部修改外部函数变量.

>>> def fun2():
    x = 123
    def fun3():
        nonlocal x
        x+=1
        return x
    return fun3()

>>> fun2()
124
1632913-20190401221555984-1719527451.png

转载于:https://www.cnblogs.com/jiajiaba/p/10639628.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值