Python3 关键字global和nonlocal

1 在函数中如果希望修改局部变量的值,需要使用global关键字

count = 5
def func():
    global count
    count = 10
    print(count)

func()
print(count)

2 内嵌函数(内部函数)

即 在一个函数内部定义另一个函数

 def fun1():
     print('func1')
     def fun2():#只能在fun1()内部调用,作用于很窄
         print('func2')
     fun2()
 fun1()

 def Fun1(x):
     def Fun2(y):#只能在fun1()内部调用,作用于很窄
         return x*y
     return Fun2
 print(Fun1(3)(4))

在内嵌函数中,如果需要在内部函数中修改外部函数的局部变量,需要使用nonlocal关键字

def fun1():
    x = 5
    def fun2():#只能在fun1()内部调用,作用于很窄
        nonlocal x #用于内嵌函数,声明使用的是外部变量
        x *= 5
        return x
    return fun2
print(fun1()())

def a():
    def b():
        print('aaaa')
    return b()
a()

example

def A():
    x = 5
    def B():
        nonlocal x
        x += 1
        return x
    return B
a = A()
print(a())  #5
print(a())  #6
print(a())  #7
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值