python的嵌套函数和闭包

嵌套函数

1.如果在一个函数内部定义了另一个函数,我们称外部的函数为外函数,内部的函数为内函数

def testfunc():
    def func1():
        return "This is func1"
    def func2():
        return "This is func2"

    print(func1())
    print(func2())
    print("Now you are back in testfunc()")
testfunc()
This is func1
This is func2
Now you are back in testfunc()

testfunc1()和testfunc2()在函数testfunc()之外是不能访问的。
例如:
在函数testfunc()之外调用func1()会报错:

NameError: name ‘func1’ is not defined

2.内函数访问外函数的变量
内函数直接访问直接访问外函数的不可变数据类型会报错Unresolved reference,使用以下两种方法来解决:
方法1 使用nonlocal nonlocal声明的变量不是局部变量,也不是全局变量,而是外部嵌套函数内的变量
方法2 把闭包变量修改成可变数据类型

def outer_func(a):
    b = 1
    c = [a]

    def inner_func():
        nonlocal b
        b += 1
        c[0] += 1
        print(c[0], b)

    inner_func()


if __name__ == '__main__':
    outer_func(5)

3.嵌套函数的使用场景
当需要多次调用某个函数时,如果将那些额外工作的代码放在外部函数,就可以减少多次调用导致的不必要开销,提高程序的运行效率

def outer_func():
    def add_func(a, b):
        return a + b

    x, y = 1, 2
    z = add_func(x, y)
    print(z)


if __name__ == '__main__':
    outer_func()

闭包

在一些语言中,在函数中可以(嵌套)定义另一个函数时,如果内部的函数引用了外部的函数的变量,则可能产生闭包。闭包可以用来在一个函数与一组“私有”变量之间创建关联关系。在给定函数被多次调用的过程中,这些私有变量能够保持其持久性。 – 维基百科
1.闭包的使用

def testfunc(n):
    print("Now you are in testfunc()")
    def func1():
        return "This is func1"
    def func2():
        return "This is func2"
    return func1 if n==1 else func2
tt=testfunc(1)
print(tt)
print(tt())
#Now you are in testfunc()
#<function testfunc.<locals>.func1 at 0x000001FDE78EBCA8>
#This is func1

2.闭包的返回值
闭包中外部函数返回的不是一个具体的值,而是一个函数。一般情况下,返回的函数会赋值给一个变量,这个变量可以在后面被继续执行调用,也就是上面说的“持久化”

def outer_func(a):
    def inner_func(z):
        print(a + z)
    return inner_func


if __name__ == '__main__':
    demo = outer_func(5)
    demo(1)
    demo(2)

3.闭包的使用场景
主要是结合装饰器使用:


def funcA(func):
    def funcB():
        func()
        print("This is funcB!")
    return funcB  #返回一个函数用于被调用

@funcA
def funcD():
    print("This is funcD!")


if __name__ == '__main__':
    funcD()

# This is funcD!
# This is funcB!

装饰器使用参考

  • 8
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值