Python 函数 闭包

在函数嵌套的前提下,内层函数引用了外层函数的变量(包括参数),外层函数,又把内层函数,当做返回值进行返回,内层函数所引用外层变量称为闭包。

def test():
    a = 10
    def test2():
        print(a)
    
    return test2

newFunc = test()
newFunc()

10
应用场景:外层函数,根据不同的参数,来生成不同作用功能的函数。

def line_config(content, length):
    def line():
        print('-' * (length // 2) + content + '-' * (length // 2))
    return line

line1 = line_config('闭包', 40)

line1()

line2 = line_config('xxx', 80)

line2()

--------------------闭包--------------------
----------------------------------------xxx----------------------------------------

  • 闭包中,如果要修改引用的外部变量,需要用nonlocal 变量声明,否则当作是闭包内,新定义的变量。
def test():
    num = 10
    def test2():
        nonlocal num
        num = 666
        print(num)
    
    print(num)
    test2()
    print(num)
    
    return test2

result = test()

10
666
666

  • 当闭包内,引用了一个,后期会发生变化的变量时,一定要注意,当函数被调用的时候,才会真正的确定对应的值,之前都是以普通的变量标识名称而存在。
def test():
    a = 1
    def test2():
        print(a)
    a = 2
    
    return test2

newFunc = test()

newFunc()

2

def test():
    funcs = []
    for i in range(1, 4):
        def test2():
            print(i)
        funcs.append(test2)
    return funcs

newFuncs = test()

print(newFuncs)

newFuncs[0]()
newFuncs[1]()
newFuncs[2]()

[<function test..test2 at 0x044006F0>, <function test..test2 at 0x04400738>, <function test..test2 at 0x04400780>]
3
3
3

def test():
    funcs = []
    for i in range(1, 4):
        def test2(num):
            def inner():
                print(num)
            return inner
        funcs.append(test2(i))
    return funcs

newFuncs = test()

print(newFuncs)

newFuncs[0]()
newFuncs[1]()
newFuncs[2]()

[<function test..test2..inner at 0x03C70780>, <function test..test2..inner at 0x03C70738>, <function test..test2..inner at 0x03C707C8>]
1
2
3

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值