python中的闭包

什么是闭包?

如果一个函数里面定义了另外一个函数,里面定义的函数使用了外面函数中定义的变量,并且外面的函数返回了里面的函数的引用,那么称里面的函数为闭包。如下面代码中hello函数就是一个闭包。

def greet1(name):
    print('outter')
    def hello():
        print('hello,my name is %s' % name)
    return hello
func1 = greet1('liming')
#打印outter,func1拿到hello函数的引用
func1()
#打印hello,my name is liming

nonlocal关键字

如果想要在闭包中修改外面函数中的变量,则应该在闭包中使用nonlocal关键字对变量进行标识。

def greet2(name: object) -> object:
    print('outter name is %s' % name)
    def say_hello():
        nonlocal name
        name += 'liu'
        print('innner name is %s' % name)

    return  say_hello
greet2('liming')()
#utter name is liming
#innner name is limingliu

小实例:使用闭包实现y=2x+1和y=2x+2两个算式的值

def func(option):
    """
    使用option选择需要初始化的函数
    func1为y=2x+1
    func2为y=2x+2
    """
    if option == 1:
        def func1(x):
            return 2*x+1
        return func1
    elif option == 2:
        def func2(x):
            return 2*x+2
        return func2
    else:
        print("error")

print(func(1)(2))
#得到结果:5
print(func(2)(2))
#得到结果:6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值